]> git.basschouten.com Git - openhab-addons.git/blob
7b0c457c46e3d1c7c31f0639810611088f4515b0
[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 /**
14  * The {@link Shelly1CoIoTVersion1} implements the parsing for CoIoT version 1
15  *
16  * @author Markus Michels - Initial contribution
17  */
18 package org.openhab.binding.shelly.internal.api1;
19
20 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
21 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
22 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
23
24 import java.util.List;
25 import java.util.Map;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrBlk;
30 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrSen;
31 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotSensor;
32 import org.openhab.binding.shelly.internal.handler.ShellyColorUtils;
33 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.OpenClosedType;
36 import org.openhab.core.library.unit.SIUnits;
37 import org.openhab.core.library.unit.Units;
38 import org.openhab.core.types.State;
39 import org.openhab.core.types.UnDefType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * The {@link Shelly1CoIoTVersion1} implements the parsing for CoIoT version 2
45  *
46  * @author Markus Michels - Initial contribution
47  */
48 @NonNullByDefault
49 public class Shelly1CoIoTVersion2 extends Shelly1CoIoTProtocol implements Shelly1CoIoTInterface {
50     private final Logger logger = LoggerFactory.getLogger(Shelly1CoIoTVersion2.class);
51     private int lastCfgCount = -1;
52
53     public Shelly1CoIoTVersion2(String thingName, ShellyThingInterface thingHandler, Map<String, CoIotDescrBlk> blkMap,
54             Map<String, CoIotDescrSen> sensorMap) {
55         super(thingName, thingHandler, blkMap, sensorMap);
56     }
57
58     @Override
59     public int getVersion() {
60         return Shelly1CoapJSonDTO.COIOT_VERSION_2;
61     }
62
63     /**
64      * Process CoIoT status update message. If a status update is received, but the device description has not been
65      * received yet a GET is send to query device description.
66      *
67      * @param sensorUpdates Complete list of sensor updates
68      * @param sen The specific sensor update to handle
69      * @param updates Resulting updates (new updates will be added to input list)
70      */
71     @Override
72     public boolean handleStatusUpdate(List<CoIotSensor> sensorUpdates, CoIotDescrSen sen, int serial, CoIotSensor s,
73             Map<String, State> updates, ShellyColorUtils col) {
74         // first check the base implementation
75         if (super.handleStatusUpdate(sensorUpdates, sen, s, updates, col)) {
76             // process by the base class
77             return true;
78         }
79
80         // Process status information and convert into channel updates
81         // Integer rIndex = Integer.parseInt(sen.links) + 1;
82         int rIndex = getIdFromBlk(sen);
83         String rGroup = getProfile().numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL
84                 : CHANNEL_GROUP_RELAY_CONTROL + rIndex;
85         String mGroup = profile.numMeters <= 1 ? CHANNEL_GROUP_METER
86                 : CHANNEL_GROUP_METER + (profile.isEMeter ? getIdFromBlk(sen) : rIndex);
87
88         boolean processed = true;
89         double value = getDouble(s.value);
90         String reason = "";
91
92         if (profile.isTRV) {
93             // Special handling for TRV, because it uses duplicate ID values with different meanings
94             switch (sen.id) {
95                 case "3101": // current temp
96                     if (value != SHELLY_API_INVTEMP) {
97                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
98                                 toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
99                     }
100                     break;
101                 case "3103": // target temp in C. 4/31, 999=unknown
102                     updateChannel(updates, CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_SETTEMP,
103                             toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
104                     break;
105                 case "3116": // S, valveError, 0/1
106                     if (s.value == 1) {
107                         thingHandler.postEvent(ALARM_TYPE_VALVE_ERROR, false);
108                     }
109                     break;
110                 case "3117": // S, mode, 0-5 (0=disabled)
111                     value = getDouble(s.value).intValue();
112                     updateChannel(updates, CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE,
113                             getStringType(profile.getValueProfile(0, (int) value)));
114                     updateChannel(updates, CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_SCHEDULE, getOnOff(value > 0));
115                     break;
116                 case "3118": // Valve state
117                     updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
118                             value != 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
119                     break;
120                 case "3121": // valvePos, Type=S, Range=0/100;
121                     boolean updated = updateChannel(updates, CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_POSITION,
122                             s.value != -1 ? toQuantityType(getDouble(s.value), 0, Units.PERCENT) : UnDefType.UNDEF);
123                     if (updated && s.value >= 0 && s.value != thingHandler.getChannelDouble(CHANNEL_GROUP_CONTROL,
124                             CHANNEL_CONTROL_POSITION)) {
125                         logger.debug("{}: Valve position changed, force update", thingName);
126                         thingHandler.requestUpdates(1, false);
127                     }
128                     break;
129                 case "3122": // boost mode, Type=S, Range=0/1
130                     updateChannel(updates, CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BCONTROL, getOnOff(value > 0));
131                     break;
132                 default:
133                     processed = false;
134             }
135         } else {
136             processed = false;
137         }
138
139         if (processed) {
140             return true;
141         }
142
143         processed = true;
144         switch (sen.id) {
145             case "3106": // L, luminosity, lux, U32, -1
146             case "3110": // S, luminosityLevel, dark/twilight/bright, "unknown"=unknown
147             case "3111": // B, battery, 0-100%, unknown -1
148             case "3112": // S, charger, 0/1
149             case "3115": // S, sensorError, 0/1
150                 // processed by base handler
151                 break;
152
153             case "6109": // P, overpowerValue, W, U32
154             case "9101":
155                 // Relay: S, mode, relay/roller or
156                 // Dimmer: S, mode, color/white
157                 // skip, could check against thing mode...
158                 break;
159
160             case "1101": // relay_0: output, 0/1
161             case "1201": // relay_1: output, 0/1
162             case "1301": // relay_2: output, 0/1
163             case "1401": // relay_3: output, 0/1
164                 updatePower(profile, updates, rIndex, sen, s, sensorUpdates);
165                 break;
166             case "1102": // roler_0: S, roller, open/close/stop -> roller state
167                 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_STATE, getStringType(s.valueStr));
168                 break;
169             case "1103": // roller_0: S, rollerPos, 0-100, unknown -1
170                 int pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min((int) value, SHELLY_MAX_ROLLER_POS));
171                 logger.debug("{}: CoAP update roller position: control={}, position={}", thingName,
172                         SHELLY_MAX_ROLLER_POS - pos, pos);
173                 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_CONTROL,
174                         toQuantityType((double) (SHELLY_MAX_ROLLER_POS - pos), Units.PERCENT));
175                 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_POS,
176                         toQuantityType((double) pos, Units.PERCENT));
177                 break;
178             case "1105": // Gas: S, valve, closed/opened/not_connected/failure/closing/opening/checking or unknown
179                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VALVE, getStringType(s.valueStr));
180                 break;
181
182             case "2101": // Input_0: S, input, 0/1
183             case "2201": // Input_1: S, input, 0/1
184             case "2301": // Input_2: S, input, 0/1
185             case "2401": // Input_3: S, input, 0/1
186                 handleInput(sen, s, rGroup, updates);
187                 break;
188             case "2102": // Input_0: EV, inputEvent, S/SS/SSS/L
189             case "2202": // Input_1: EV, inputEvent
190             case "2302": // Input_2: EV, inputEvent
191             case "2402": // Input_3: EV, inputEvent
192                 handleInputEvent(sen, getString(s.valueStr), -1, serial, updates);
193                 break;
194             case "2103": // EVC, inputEventCnt, U16
195             case "2203": // EVC, inputEventCnt, U16
196             case "2303": // EVC, inputEventCnt, U16
197             case "2403": // EVC, inputEventCnt, U16
198                 handleInputEvent(sen, "", getInteger((int) s.value), serial, updates);
199                 break;
200             case "3101": // sensor_0: T, extTemp, C, -55/125; unknown 999
201             case "3201": // sensor_1: T, extTemp, C, -55/125; unknown 999
202             case "3301": // sensor_2: T, extTemp, C, -55/125; unknown 999
203                 int idx = getExtTempId(sen.id);
204                 if (idx >= 0 && value != SHELLY_API_INVTEMP) {
205                     // H&T, Fllod, DW only have 1 channel, 1/1PM with Addon have up to to 3 sensors
206                     String channel = profile.isSensor ? CHANNEL_SENSOR_TEMP : CHANNEL_SENSOR_TEMP + idx;
207                     // Some devices report values = -999 or 99 during fw update
208                     updateChannel(updates, CHANNEL_GROUP_SENSOR, channel,
209                             toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
210                 } else {
211                     logger.debug("{}: Unable to get extSensorId {} from {}/{}", thingName, sen.id, sen.type, sen.desc);
212                 }
213                 break;
214             case "3104": // T, deviceTemp, Celsius -40/300; 999=unknown
215                 if ("targetTemp".equalsIgnoreCase(sen.desc)) {
216                     break; // target temp in F-> ignore
217                 }
218                 // sensor_0: T, internalTemp, F, 39/88, unknown 999
219                 updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
220                         toQuantityType(value, DIGITS_NONE, SIUnits.CELSIUS));
221                 break;
222             case "3102": // sensor_0: T, extTemp, F, -67/257, unknown 999
223             case "3202": // sensor_1: T, extTemp, F, -67/257, unknown 999
224             case "3302": // sensor_2: T, extTemp, F, -67/257, unknown 999
225             case "3105": // T, deviceTemp, Fahrenheit -40/572
226                 // skip, we use only C
227                 break;
228
229             case "3107": // C, Gas concentration, U16
230                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, getDecimal(s.value));
231                 break;
232             case "3108": // DW: S, dwIsOpened, 0/1, -1=unknown
233                 if (value != -1) {
234                     updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
235                             value != 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
236                 } else {
237                     logger.debug("{}: Sensor error reported, check device, battery and installation", thingName);
238                 }
239                 break;
240             case "3109": // S, tilt, 0-180deg, -1
241                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
242                         toQuantityType(s.value, DIGITS_NONE, Units.DEGREE_ANGLE));
243                 break;
244             case "3113": // S, sensorOp, warmup/normal/fault
245                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE, getStringType(s.valueStr));
246                 break;
247             case "3114": // S, selfTest, not_completed/completed/running/pending
248                 updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST, getStringType(s.valueStr));
249                 break;
250             case "3117": // S, extInput, 0/1
251                 handleInput(sen, s, rGroup, updates);
252                 break;
253             case "3118":
254                 updateChannel(updates, mGroup, CHANNEL_SENSOR_VOLTAGE,
255                         toQuantityType(getDouble(s.value), 2, Units.VOLT));
256                 break;
257
258             case "4101": // relay_0/light_0: P, power, W
259             case "4201": // relay_1/light_1: P, power, W
260             case "4301": // relay_2/light_2: P, power, W
261             case "4401": // relay_3/light_3: P, power, W
262             case "4105": // emeter_0: P, power, W
263             case "4205": // emeter_1: P, power, W
264             case "4305": // emeter_2: P, power, W
265             case "4102": // roller_0: P, rollerPower, W, 0-2300, unknown -1
266             case "4202": // roller_1: P, rollerPower, W, 0-2300, unknown -1
267                 updateChannel(updates, mGroup, CHANNEL_METER_CURRENTWATTS,
268                         toQuantityType(s.value, DIGITS_WATT, Units.WATT));
269                 if (!profile.isRGBW2 && !profile.isRoller) {
270                     // only for regular, not-aggregated meters
271                     updateChannel(updates, mGroup, CHANNEL_LAST_UPDATE, getTimestamp());
272                 }
273                 break;
274
275             case "4103": // relay_0: E, energy, Wmin, U32
276             case "4203": // relay_1: E, energy, Wmin, U32
277             case "4303": // relay_2: E, energy, Wmin, U32
278             case "4403": // relay_3: E, energy, Wmin, U32
279             case "4104": // roller_0: E, rollerEnergy, Wmin, U32, -1
280             case "4204": // roller_0: E, rollerEnergy, Wmin, U32, -1
281             case "4106": // emeter_0: E, energy, Wh, U32
282             case "4206": // emeter_1: E, energy, Wh, U32
283             case "4306": // emeter_2: E, energy, Wh, U32
284                 double total = profile.isEMeter ? s.value / 1000 : s.value / 60 / 1000;
285                 updateChannel(updates, mGroup, CHANNEL_METER_TOTALKWH,
286                         toQuantityType(total, DIGITS_KWH, Units.KILOWATT_HOUR));
287                 break;
288
289             case "4107": // emeter_0: E, energyReturned, Wh, U32, -1
290             case "4207": // emeter_1: E, energyReturned, Wh, U32, -1
291             case "4307": // emeter_2: E, energyReturned, Wh, U32, -1
292                 updateChannel(updates, mGroup, CHANNEL_EMETER_TOTALRET,
293                         toQuantityType(getDouble(s.value) / 1000, DIGITS_KWH, Units.KILOWATT_HOUR));
294                 break;
295
296             case "4108": // emeter_0: V, voltage, 0-265V, U32, -1
297             case "4208": // emeter_1: V, voltage, 0-265V, U32, -1
298             case "4308": // emeter_2: V, voltage, 0-265V, U32, -1
299                 updateChannel(updates, mGroup, CHANNEL_EMETER_VOLTAGE,
300                         toQuantityType(getDouble(s.value), DIGITS_VOLT, Units.VOLT));
301                 break;
302
303             case "4109": // emeter_0: A, current, 0/120A, -1
304             case "4209": // emeter_1: A, current, 0/120A, -1
305             case "4309": // emeter_2: A, current, 0/120A, -1
306                 updateChannel(updates, rGroup, CHANNEL_EMETER_CURRENT,
307                         toQuantityType(getDouble(s.value), DIGITS_VOLT, Units.AMPERE));
308                 break;
309
310             case "4110": // emeter_0: S, powerFactor, 0/1, -1
311             case "4210": // emeter_1: S, powerFactor, 0/1, -1
312             case "4310": // emeter_2: S, powerFactor, 0/1, -1
313                 updateChannel(updates, rGroup, CHANNEL_EMETER_PFACTOR, getDecimal(s.value));
314                 break;
315
316             case "5101": // {"I":5101,"T":"S","D":"brightness","R":"0/100","L":1},
317             case "5102": // {"I":5102,"T":"S","D":"gain","R":"0/100","L":1},
318             case "5103": // {"I":5103,"T":"S","D":"colorTemp","U":"K","R":"3000/6500","L":1},
319             case "5105": // {"I":5105,"T":"S","D":"red","R":"0/255","L":1},
320             case "5106": // {"I":5106,"T":"S","D":"green","R":"0/255","L":1},
321             case "5107": // {"I":5107,"T":"S","D":"blue","R":"0/255","L":1},
322             case "5108": // {"I":5108,"T":"S","D":"white","R":"0/255","L":1},
323                 // already covered by base handler
324                 break;
325
326             case "6101": // A, overtemp, 0/1
327                 if (s.value == 1) {
328                     thingHandler.postEvent(ALARM_TYPE_OVERTEMP, true);
329                 }
330                 break;
331             case "6102": // relay_0: A, overpower, 0/1
332             case "6202": // relay_1: A, overpower, 0/1
333             case "6302": // relay_2: A, overpower, 0/1
334             case "6402": // relay_3: A, overpower, 0/1
335                 if (s.value == 1) {
336                     thingHandler.postEvent(ALARM_TYPE_OVERPOWER, true);
337                 }
338                 break;
339             case "6104": // relay_0: A, loadError, 0/1
340             case "6204": // relay_1: A, loadError, 0/1
341             case "6304": // relay_2: A, loadError, 0/1
342             case "6404": // relay_3: A, loadError, 0/1
343                 if (s.value == 1) {
344                     thingHandler.postEvent(ALARM_TYPE_LOADERR, true);
345                 }
346                 break;
347             case "6103": // roller_0: A, rollerStopReason, normal/safety_switch/obstacle/overpower
348                 reason = getString(s.valueStr);
349                 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_STOPR, getStringType(reason));
350                 if (!reason.isEmpty() && !reason.equalsIgnoreCase(SHELLY_API_STOPR_NORMAL)) {
351                     thingHandler.postEvent("ROLLER_" + reason.toUpperCase(), true);
352                 }
353             case "6106": // A, flood, 0/1, -1
354                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD, OnOffType.from(value == 1));
355                 break;
356
357             case "6107": // A, motion, 0/1, -1
358                 // {"I":6107,"T":"A","D":"motion","R":["0/1","-1"],"L":1},
359                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION, OnOffType.from(value == 1));
360                 break;
361             case "3119": // Motion timestamp (timestamp os GMT, not adapted to the adapted timezone)
362                 // {"I":3119,"T":"S","D":"timestamp","U":"s","R":["U32","-1"],"L":1},
363                 if (s.value != 0) {
364                     updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_TS,
365                             getTimestamp(getString("GMT"), (long) s.value));
366                 }
367                 break;
368             case "3120": // motionActive (timestamp os GMT, not adapted to the adapted timezone)
369                 // {"I":3120,"T":"S","D":"motionActive","R":["0/1","-1"],"L":1},
370                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_ACT,
371                         getTimestamp("GMT", (long) s.value));
372                 break;
373
374             case "6108": // A, gas, none/mild/heavy/test or unknown
375                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE, getStringType(s.valueStr));
376                 break;
377             case "6110": // A, vibration, 0/1, -1=unknown
378                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VIBRATION, OnOffType.from(s.value == 1));
379                 if (s.value == 1) {
380                     // post event
381                     thingHandler.triggerChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM, EVENT_TYPE_VIBRATION);
382                 }
383                 break;
384             case "9102": // EV, wakeupEvent, battery/button/periodic/poweron/sensor/ext_power, "unknown"=unknown
385                 if (!s.valueArray.isEmpty()) {
386                     thingHandler.updateWakeupReason(s.valueArray);
387                     lastWakeup = (String) s.valueArray.get(0);
388                 }
389                 break;
390             case "9103": // EVC, cfgChanged, U16
391                 if (lastCfgCount == -1 || lastCfgCount != s.value) {
392                     thingHandler.requestUpdates(1, true); // refresh config
393                 }
394                 lastCfgCount = (int) s.value;
395                 break;
396
397             default:
398                 processed = false;
399         }
400         return processed;
401     }
402
403     @Override
404     public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
405         return super.fixDescription(sen, blkMap);
406     }
407
408     private static final String ID_4101_DESCR = "{ \"I\":4101, \"T\":\"P\", \"D\":\"power\",  \"U\": \"W\",    \"R\":\"0/3500\", \"L\": 1}";
409     private static final String ID_4103_DESCR = "{ \"I\":4103, \"T\":\"E\", \"D\":\"energy\", \"U\": \"Wmin\", \"R\":\"U32\", \"L\": 1}";
410
411     @Override
412     public void completeMissingSensorDefinition(Map<String, CoIotDescrSen> sensorMap) {
413         if (profile.isDuo && profile.inColor) {
414             addSensor(sensorMap, "4101", ID_4101_DESCR);
415             addSensor(sensorMap, "4103", ID_4103_DESCR);
416         }
417         super.completeMissingSensorDefinition(sensorMap);
418     }
419 }