]> git.basschouten.com Git - openhab-addons.git/blob
c650efeea7fdbf7def898f76012e94bd039c811f
[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.coap.ShellyCoapJSonDTO.CoIotDescrBlk;
25 import org.openhab.binding.shelly.internal.coap.ShellyCoapJSonDTO.CoIotDescrSen;
26 import org.openhab.binding.shelly.internal.coap.ShellyCoapJSonDTO.CoIotSensor;
27 import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
28 import org.openhab.binding.shelly.internal.handler.ShellyColorUtils;
29 import org.openhab.core.library.types.OnOffType;
30 import org.openhab.core.library.unit.ImperialUnits;
31 import org.openhab.core.library.unit.SIUnits;
32 import org.openhab.core.library.unit.Units;
33 import org.openhab.core.types.State;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The {@link ShellyCoIoTVersion1} implements the parsing for CoIoT version 1
39  *
40  * @author Markus Michels - Initial contribution
41  */
42 @NonNullByDefault
43 public class ShellyCoIoTVersion1 extends ShellyCoIoTProtocol implements ShellyCoIoTInterface {
44     private final Logger logger = LoggerFactory.getLogger(ShellyCoIoTVersion1.class);
45
46     public ShellyCoIoTVersion1(String thingName, ShellyBaseHandler thingHandler, Map<String, CoIotDescrBlk> blkMap,
47             Map<String, CoIotDescrSen> sensorMap) {
48         super(thingName, thingHandler, blkMap, sensorMap);
49     }
50
51     @Override
52     public int getVersion() {
53         return ShellyCoapJSonDTO.COIOT_VERSION_1;
54     }
55
56     /**
57      * Process CoIoT status update message. If a status update is received, but the device description has not been
58      * received yet a GET is send to query device description.
59      *
60      * @param devId device id included in the status packet
61      * @param payload CoAP payload (Json format), example: {"G":[[0,112,0]]}
62      * @param serial Serial for this request. If this the the same as last serial
63      *            the update was already sent and processed so this one gets
64      *            ignored.
65      */
66     @Override
67     public boolean handleStatusUpdate(List<CoIotSensor> sensorUpdates, CoIotDescrSen sen, int serial, CoIotSensor s,
68             Map<String, State> updates, ShellyColorUtils col) {
69         // first check the base implementation
70         if (super.handleStatusUpdate(sensorUpdates, sen, s, updates, col)) {
71             // process by the base class
72             return true;
73         }
74
75         // Process status information and convert into channel updates
76         Integer rIndex = Integer.parseInt(sen.links) + 1;
77         String rGroup = getProfile().numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL
78                 : CHANNEL_GROUP_RELAY_CONTROL + rIndex;
79         switch (sen.type.toLowerCase()) {
80             case "t": // Temperature +
81                 Double value = getDouble(s.value);
82                 switch (sen.desc.toLowerCase()) {
83                     case "temperature": // Sensor Temp
84                         if (getString(getProfile().settings.temperatureUnits)
85                                 .equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT)) {
86                             value = ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(getDouble(s.value))
87                                     .doubleValue();
88                         }
89                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
90                                 toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
91                         break;
92                     case "temperature f": // Device Temp -> ignore (we use C only)
93                         break;
94                     case "temperature c": // Device Temp in C
95                         // Device temperature
96                         updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
97                                 toQuantityType(value, DIGITS_NONE, SIUnits.CELSIUS));
98                         break;
99                     case "external temperature f": // Shelly 1/1PM external temp sensors
100                         // ignore F, we use C only
101                         break;
102                     case "external temperature c": // Shelly 1/1PM external temp sensors
103                     case "external_temperature":
104                         int idx = getExtTempId(sen.id);
105                         if (idx > 0) {
106                             updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP + idx,
107                                     toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
108                         } else {
109                             logger.debug("{}: Unable to get extSensorId {} from {}/{}", thingName, sen.id, sen.type,
110                                     sen.desc);
111                         }
112                         break;
113                     default:
114                         logger.debug("{}: Unknown temperatur type: {}", thingName, sen.desc);
115                 }
116                 break;
117             case "p": // Power/Watt
118                 // 3EM uses 1-based meter IDs, other 0-based
119                 String mGroup = profile.numMeters == 1 ? CHANNEL_GROUP_METER
120                         : CHANNEL_GROUP_METER + (profile.isEMeter ? sen.links : rIndex);
121                 updateChannel(updates, mGroup, CHANNEL_METER_CURRENTWATTS,
122                         toQuantityType(s.value, DIGITS_WATT, Units.WATT));
123                 updateChannel(updates, mGroup, CHANNEL_LAST_UPDATE, getTimestamp());
124                 break;
125             case "s" /* CatchAll */:
126                 switch (sen.desc.toLowerCase()) {
127                     case "overtemp":
128                         if (s.value == 1) {
129                             thingHandler.postEvent(ALARM_TYPE_OVERTEMP, true);
130                         }
131                         break;
132                     case "energy counter 0 [w-min]":
133                         updateChannel(updates, rGroup, CHANNEL_METER_LASTMIN1,
134                                 toQuantityType(s.value, DIGITS_WATT, Units.WATT));
135                         break;
136                     case "energy counter 1 [w-min]":
137                     case "energy counter 2 [w-min]":
138                         // we don't use them
139                         break;
140                     case "energy counter total [w-h]": // 3EM reports W/h
141                     case "energy counter total [w-min]":
142                         Double total = profile.isEMeter ? s.value / 1000 : s.value / 60 / 1000;
143                         updateChannel(updates, rGroup, CHANNEL_METER_TOTALKWH,
144                                 toQuantityType(total, DIGITS_KWH, Units.KILOWATT_HOUR));
145                         break;
146                     case "voltage":
147                         updateChannel(updates, rGroup, CHANNEL_EMETER_VOLTAGE,
148                                 toQuantityType(getDouble(s.value), DIGITS_VOLT, Units.VOLT));
149                         break;
150                     case "current":
151                         updateChannel(updates, rGroup, CHANNEL_EMETER_CURRENT,
152                                 toQuantityType(getDouble(s.value), DIGITS_VOLT, Units.AMPERE));
153                         break;
154                     case "pf":
155                         updateChannel(updates, rGroup, CHANNEL_EMETER_PFACTOR, getDecimal(s.value));
156                         break;
157                     case "position":
158                         // work around: Roller reports 101% instead max 100
159                         double pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min(s.value, SHELLY_MAX_ROLLER_POS));
160                         updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_CONTROL,
161                                 toQuantityType(SHELLY_MAX_ROLLER_POS - pos, Units.PERCENT));
162                         updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_POS,
163                                 toQuantityType(pos, Units.PERCENT));
164                         break;
165                     case "input event": // Shelly Button 1
166                         handleInputEvent(sen, getString(s.valueStr), -1, serial, updates);
167                         break;
168                     case "input event counter": // Shelly Button 1/ix3
169                         handleInputEvent(sen, "", getInteger((int) s.value), serial, updates);
170                         break;
171                     case "flood":
172                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
173                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
174                         break;
175                     case "tilt": // DW with FW1.6.5+ //+
176                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
177                                 toQuantityType(s.value, DIGITS_NONE, Units.DEGREE_ANGLE));
178                         break;
179                     case "vibration": // DW with FW1.6.5+
180                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VIBRATION,
181                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
182                         break;
183                     case "temp": // Shelly Bulb
184                     case "colortemperature": // Shelly Duo
185                         updateChannel(updates,
186                                 profile.inColor ? CHANNEL_GROUP_COLOR_CONTROL : CHANNEL_GROUP_WHITE_CONTROL,
187                                 CHANNEL_COLOR_TEMP,
188                                 ShellyColorUtils.toPercent((int) s.value, profile.minTemp, profile.maxTemp));
189                         break;
190                     case "sensor state": // Shelly Gas
191                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE, getStringType(s.valueStr));
192                         break;
193                     case "alarm state": // Shelly Gas
194                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
195                                 getStringType(s.valueStr));
196                         break;
197                     case "self-test state":// Shelly Gas
198                         updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
199                                 getStringType(s.valueStr));
200                         break;
201                     case "concentration":// Shelly Gas
202                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, getDecimal(s.value));
203                         break;
204                     case "sensorerror":
205                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR, getStringType(s.valueStr));
206                         break;
207                     default:
208                         // Unknown
209                         return false;
210                 }
211                 break;
212
213             default:
214                 // Unknown type
215                 return false;
216         }
217         return true;
218     }
219
220     /**
221      *
222      * Depending on the device type and firmware release there are significant bugs or incosistencies in the CoIoT
223      * Device Description returned by the discovery request. Shelly is even not following it's own speicifcation. All of
224      * that has been reported to Shelly and acknowledged. Firmware 1.6 brought significant improvements. However, the
225      * old mapping stays in to support older firmware releases.
226      *
227      * @param sen Sensor description received from device
228      * @return fixed Sensor description (sen)
229      */
230     @Override
231     public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
232         // Shelly1: reports null descr+type "Switch" -> map to S
233         // Shelly1PM: reports null descr+type "Overtemp" -> map to O
234         // Shelly1PM: reports null descr+type "W" -> add description
235         // Shelly1PM: reports temp senmsors without desc -> add description
236         // Shelly Dimmer: sensors are reported without descriptions -> map to S
237         // SHelly Sense: multiple issues: Description should not be lower case, invalid type for Motion and Battery
238         // Shelly Sense: Battery is reported with Desc "battery", but type "H" instead of "B"
239         // Shelly Sense: Motion is reported with Desc "battery", but type "H" instead of "B"
240         // Shelly Bulb: Colors are coded with Type="Red" etc. rather than Type="S" and color as Descr
241         // Shelly RGBW2 is reporting Brightness, Power, VSwitch for each channel, but all with L=0
242         if (sen == null) {
243             throw new IllegalArgumentException("sen should not be null!");
244         }
245         if (sen.desc == null) {
246             sen.desc = "";
247         }
248         String desc = sen.desc.toLowerCase();
249
250         // RGBW2 reports Power_0, Power_1, Power_2, Power_3; same for VSwitch and Brightness, all of them linkted to L:0
251         // we break it up to Power with L:0, Power with L:1...
252         if (desc.contains("_") && (desc.contains("power") || desc.contains("vswitch") || desc.contains("brightness"))) {
253             String newDesc = substringBefore(sen.desc, "_");
254             String newLink = substringAfter(sen.desc, "_");
255             sen.desc = newDesc;
256             sen.links = newLink;
257             if (!blkMap.containsKey(sen.links)) {
258                 // auto-insert a matching blk entry
259                 CoIotDescrBlk blk = new CoIotDescrBlk();
260                 CoIotDescrBlk blk0 = blkMap.get("0"); // blk 0 is always there
261                 blk.id = sen.links;
262                 if (blk0 != null) {
263                     blk.desc = blk0.desc + "_" + blk.id;
264                     blkMap.put(blk.id, blk);
265                 }
266             }
267         }
268
269         switch (sen.type.toLowerCase()) {
270             case "w": // old devices/firmware releases use "W", new ones "P"
271                 sen.type = "P";
272                 sen.desc = "Power";
273                 break;
274             case "tc":
275                 sen.type = "T";
276                 sen.desc = "Temperature C";
277                 break;
278             case "tf":
279                 sen.type = "T";
280                 sen.desc = "Temperature F";
281                 break;
282             case "overtemp":
283                 sen.type = "S";
284                 sen.desc = "Overtemp";
285                 break;
286             case "relay0":
287             case "switch":
288             case "vswitch":
289                 sen.type = "S";
290                 sen.desc = "State";
291                 break;
292         }
293
294         switch (sen.desc.toLowerCase()) {
295             case "motion": // fix acc to spec it's T=M
296                 sen.type = "M";
297                 sen.desc = "Motion";
298                 break;
299             case "battery": // fix: type is B not H
300                 sen.type = "B";
301                 sen.desc = "Battery";
302                 break;
303             case "overtemp":
304                 sen.type = "S";
305                 sen.desc = "Overtemp";
306                 break;
307             case "relay0":
308             case "switch":
309             case "vswitch":
310                 sen.type = "S";
311                 sen.desc = "State";
312                 break;
313             case "e cnt 0 [w-min]": // 4 Pro
314             case "e cnt 1 [w-min]":
315             case "e cnt 2 [w-min]":
316             case "e cnt total [w-min]": // 4 Pro
317                 sen.desc = sen.desc.toLowerCase().replace("e cnt", "energy counter");
318                 break;
319
320         }
321
322         if (sen.desc.isEmpty()) {
323             switch (sen.type.toLowerCase()) {
324                 case "p":
325                     sen.desc = "Power";
326                     break;
327                 case "T":
328                     sen.desc = "Temperature";
329                     break;
330                 case "input":
331                     sen.type = "S";
332                     sen.desc = "Input";
333                     break;
334                 case "output":
335                     sen.type = "S";
336                     sen.desc = "Output";
337                     break;
338                 case "brightness":
339                     sen.type = "S";
340                     sen.desc = "Brightness";
341                     break;
342                 case "red":
343                 case "green":
344                 case "blue":
345                 case "white":
346                 case "gain":
347                 case "temp": // Bulb: Color temperature
348                     sen.desc = sen.type;
349                     sen.type = "S";
350                     break;
351                 case "vswitch":
352                     // it seems that Shelly tends to break their own spec: T is the description and D is no longer
353                     // included -> map D to sen.T and set CatchAll for T
354                     sen.desc = sen.type;
355                     sen.type = "S";
356                     break;
357                 // Default: set no description
358                 // (there are no T values defined in the CoIoT spec)
359                 case "tostate":
360                 default:
361                     sen.desc = "";
362             }
363         }
364         return sen;
365     }
366 }