]> git.basschouten.com Git - openhab-addons.git/blob
9412162c71e0cb887d9957d0d9065c64d5a9bff6
[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.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.ShellyColorUtils;
28 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
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, ShellyThingInterface 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,
156                                 toQuantityType(getDecimal(s.value), Units.PERCENT));
157                         break;
158                     case "position":
159                         // work around: Roller reports 101% instead max 100
160                         double pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min(s.value, SHELLY_MAX_ROLLER_POS));
161                         updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_CONTROL,
162                                 toQuantityType(SHELLY_MAX_ROLLER_POS - pos, Units.PERCENT));
163                         updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_POS,
164                                 toQuantityType(pos, Units.PERCENT));
165                         break;
166                     case "input event": // Shelly Button 1
167                         handleInputEvent(sen, getString(s.valueStr), -1, serial, updates);
168                         break;
169                     case "input event counter": // Shelly Button 1/ix3
170                         handleInputEvent(sen, "", getInteger((int) s.value), serial, updates);
171                         break;
172                     case "flood":
173                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
174                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
175                         break;
176                     case "tilt": // DW with FW1.6.5+ //+
177                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
178                                 toQuantityType(s.value, DIGITS_NONE, Units.DEGREE_ANGLE));
179                         break;
180                     case "vibration": // DW with FW1.6.5+
181                         if (profile.isMotion) {
182                             // handle as status
183                             updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VIBRATION,
184                                     s.value == 1 ? OnOffType.ON : OnOffType.OFF);
185                         } else if (s.value == 1) {
186                             // handle as event
187                             thingHandler.triggerChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
188                                     EVENT_TYPE_VIBRATION);
189                         }
190                         break;
191                     case "temp": // Shelly Bulb
192                     case "colortemperature": // Shelly Duo
193                         updateChannel(updates,
194                                 profile.inColor ? CHANNEL_GROUP_COLOR_CONTROL : CHANNEL_GROUP_WHITE_CONTROL,
195                                 CHANNEL_COLOR_TEMP,
196                                 ShellyColorUtils.toPercent((int) s.value, profile.minTemp, profile.maxTemp));
197                         break;
198                     case "sensor state": // Shelly Gas
199                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE, getStringType(s.valueStr));
200                         break;
201                     case "alarm state": // Shelly Gas
202                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
203                                 getStringType(s.valueStr));
204                         break;
205                     case "self-test state":// Shelly Gas
206                         updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
207                                 getStringType(s.valueStr));
208                         break;
209                     case "concentration":// Shelly Gas
210                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM,
211                                 toQuantityType(getDouble(s.value), DIGITS_NONE, Units.PARTS_PER_MILLION));
212                         break;
213                     case "sensorerror":
214                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR, getStringType(s.valueStr));
215                         break;
216                     default:
217                         // Unknown
218                         return false;
219                 }
220                 break;
221
222             default:
223                 // Unknown type
224                 return false;
225         }
226         return true;
227     }
228
229     /**
230      *
231      * Depending on the device type and firmware release there are significant bugs or incosistencies in the CoIoT
232      * Device Description returned by the discovery request. Shelly is even not following it's own speicifcation. All of
233      * that has been reported to Shelly and acknowledged. Firmware 1.6 brought significant improvements. However, the
234      * old mapping stays in to support older firmware releases.
235      *
236      * @param sen Sensor description received from device
237      * @return fixed Sensor description (sen)
238      */
239     @Override
240     public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
241         // Shelly1: reports null descr+type "Switch" -> map to S
242         // Shelly1PM: reports null descr+type "Overtemp" -> map to O
243         // Shelly1PM: reports null descr+type "W" -> add description
244         // Shelly1PM: reports temp senmsors without desc -> add description
245         // Shelly Dimmer: sensors are reported without descriptions -> map to S
246         // SHelly Sense: multiple issues: Description should not be lower case, invalid type for Motion and Battery
247         // Shelly Sense: Battery is reported with Desc "battery", but type "H" instead of "B"
248         // Shelly Sense: Motion is reported with Desc "battery", but type "H" instead of "B"
249         // Shelly Bulb: Colors are coded with Type="Red" etc. rather than Type="S" and color as Descr
250         // Shelly RGBW2 is reporting Brightness, Power, VSwitch for each channel, but all with L=0
251         if (sen == null) {
252             throw new IllegalArgumentException("sen should not be null!");
253         }
254         if (sen.desc == null) {
255             sen.desc = "";
256         }
257         String desc = sen.desc.toLowerCase();
258
259         // RGBW2 reports Power_0, Power_1, Power_2, Power_3; same for VSwitch and Brightness, all of them linkted to L:0
260         // we break it up to Power with L:0, Power with L:1...
261         if (desc.contains("_") && (desc.contains("power") || desc.contains("vswitch") || desc.contains("brightness"))) {
262             String newDesc = substringBefore(sen.desc, "_");
263             String newLink = substringAfter(sen.desc, "_");
264             sen.desc = newDesc;
265             sen.links = newLink;
266             if (!blkMap.containsKey(sen.links)) {
267                 // auto-insert a matching blk entry
268                 CoIotDescrBlk blk = new CoIotDescrBlk();
269                 CoIotDescrBlk blk0 = blkMap.get("0"); // blk 0 is always there
270                 blk.id = sen.links;
271                 if (blk0 != null) {
272                     blk.desc = blk0.desc + "_" + blk.id;
273                     blkMap.put(blk.id, blk);
274                 }
275             }
276         }
277
278         switch (sen.type.toLowerCase()) {
279             case "w": // old devices/firmware releases use "W", new ones "P"
280                 sen.type = "P";
281                 sen.desc = "Power";
282                 break;
283             case "tc":
284                 sen.type = "T";
285                 sen.desc = "Temperature C";
286                 break;
287             case "tf":
288                 sen.type = "T";
289                 sen.desc = "Temperature F";
290                 break;
291             case "overtemp":
292                 sen.type = "S";
293                 sen.desc = "Overtemp";
294                 break;
295             case "relay0":
296             case "switch":
297             case "vswitch":
298                 sen.type = "S";
299                 sen.desc = "State";
300                 break;
301         }
302
303         switch (sen.desc.toLowerCase()) {
304             case "motion": // fix acc to spec it's T=M
305                 sen.type = "M";
306                 sen.desc = "Motion";
307                 break;
308             case "battery": // fix: type is B not H
309                 sen.type = "B";
310                 sen.desc = "Battery";
311                 break;
312             case "overtemp":
313                 sen.type = "S";
314                 sen.desc = "Overtemp";
315                 break;
316             case "relay0":
317             case "switch":
318             case "vswitch":
319                 sen.type = "S";
320                 sen.desc = "State";
321                 break;
322             case "e cnt 0 [w-min]": // 4 Pro
323             case "e cnt 1 [w-min]":
324             case "e cnt 2 [w-min]":
325             case "e cnt total [w-min]": // 4 Pro
326                 sen.desc = sen.desc.toLowerCase().replace("e cnt", "energy counter");
327                 break;
328
329         }
330
331         if (sen.desc.isEmpty()) {
332             switch (sen.type.toLowerCase()) {
333                 case "p":
334                     sen.desc = "Power";
335                     break;
336                 case "T":
337                     sen.desc = "Temperature";
338                     break;
339                 case "input":
340                     sen.type = "S";
341                     sen.desc = "Input";
342                     break;
343                 case "output":
344                     sen.type = "S";
345                     sen.desc = "Output";
346                     break;
347                 case "brightness":
348                     sen.type = "S";
349                     sen.desc = "Brightness";
350                     break;
351                 case "red":
352                 case "green":
353                 case "blue":
354                 case "white":
355                 case "gain":
356                 case "temp": // Bulb: Color temperature
357                     sen.desc = sen.type;
358                     sen.type = "S";
359                     break;
360                 case "vswitch":
361                     // it seems that Shelly tends to break their own spec: T is the description and D is no longer
362                     // included -> map D to sen.T and set CatchAll for T
363                     sen.desc = sen.type;
364                     sen.type = "S";
365                     break;
366                 // Default: set no description
367                 // (there are no T values defined in the CoIoT spec)
368                 case "tostate":
369                 default:
370                     sen.desc = "";
371             }
372         }
373         return sen;
374     }
375 }