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