]> git.basschouten.com Git - openhab-addons.git/blob
54ce5670f7ac222152434d0af182fa56f13f737c
[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.handler;
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 org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.binding.shelly.internal.api.ShellyApiException;
21 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsEMeter;
22 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsMeter;
23 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
24 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusSensor;
25 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusSensor.ShellyADC;
26 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
27 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
28 import org.openhab.core.library.types.OnOffType;
29 import org.openhab.core.library.types.OpenClosedType;
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.UnDefType;
34
35 /***
36  * The{@link ShellyComponents} implements updates for supplemental components
37  * Meter will be used by Relay + Light; Sensor is part of H&T, Flood, Door Window, Sense
38  *
39  * @author Markus Michels - Initial contribution
40  */
41 @NonNullByDefault
42 public class ShellyComponents {
43
44     /**
45      * Update device status
46      *
47      * @param th Thing Handler instance
48      * @param profile ShellyDeviceProfile
49      */
50     public static boolean updateDeviceStatus(ShellyBaseHandler thingHandler, ShellySettingsStatus status) {
51         if (!thingHandler.areChannelsCreated()) {
52             thingHandler.updateChannelDefinitions(ShellyChannelDefinitions.createDeviceChannels(thingHandler.getThing(),
53                     thingHandler.getProfile(), status));
54         }
55
56         Integer rssi = getInteger(status.wifiSta.rssi);
57         thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_UPTIME,
58                 toQuantityType((double) getLong(status.uptime), DIGITS_NONE, Units.SECOND));
59         thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_RSSI, mapSignalStrength(rssi));
60         if ((status.tmp != null) && !thingHandler.getProfile().isSensor) {
61             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
62                     toQuantityType(getDouble(status.tmp.tC), DIGITS_NONE, SIUnits.CELSIUS));
63         } else if (status.temperature != null) {
64             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
65                     toQuantityType(getDouble(status.temperature), DIGITS_NONE, SIUnits.CELSIUS));
66         }
67         thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SLEEPTIME,
68                 toQuantityType(getInteger(status.sleepTime), Units.SECOND));
69
70         thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_UPDATE, getOnOff(status.hasUpdate));
71
72         return false; // device status never triggers update
73     }
74
75     /**
76      * Update Meter channel
77      *
78      * @param th Thing Handler instance
79      * @param profile ShellyDeviceProfile
80      * @param status Last ShellySettingsStatus
81      */
82     public static boolean updateMeters(ShellyBaseHandler thingHandler, ShellySettingsStatus status) {
83         ShellyDeviceProfile profile = thingHandler.getProfile();
84
85         double accumulatedWatts = 0.0;
86         double accumulatedTotal = 0.0;
87         double accumulatedReturned = 0.0;
88
89         boolean updated = false;
90         // Devices without power meters get no updates
91         // We need to differ
92         // Roler+RGBW2 have multiple meters -> aggregate consumption to the functional device
93         // Meter and EMeter have a different set of channels
94         if ((profile.numMeters > 0) && ((status.meters != null) || (status.emeters != null))) {
95             if (!profile.isRoller && !profile.isRGBW2) {
96                 thingHandler.logger.trace("{}: Updating {} {}meter(s)", thingHandler.thingName, profile.numMeters,
97                         !profile.isEMeter ? "standard " : "e-");
98
99                 // In Relay mode we map eacher meter to the matching channel group
100                 int m = 0;
101                 if (!profile.isEMeter) {
102                     for (ShellySettingsMeter meter : status.meters) {
103                         Integer meterIndex = m + 1;
104                         if (getBool(meter.isValid) || profile.isLight) { // RGBW2-white doesn't report valid flag
105                                                                          // correctly in white mode
106                             String groupName = "";
107                             if (profile.numMeters > 1) {
108                                 groupName = CHANNEL_GROUP_METER + meterIndex.toString();
109                             } else {
110                                 groupName = CHANNEL_GROUP_METER;
111                             }
112
113                             if (!thingHandler.areChannelsCreated()) {
114                                 // skip for Shelly Bulb: JSON has a meter, but values don't get updated
115                                 if (!profile.isBulb) {
116                                     thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
117                                             .createMeterChannels(thingHandler.getThing(), meter, groupName));
118                                 }
119                             }
120
121                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
122                                     toQuantityType(getDouble(meter.power), DIGITS_WATT, Units.WATT));
123                             accumulatedWatts += getDouble(meter.power);
124
125                             // convert Watt/Min to kw/h
126                             if (meter.total != null) {
127                                 double kwh = getDouble(meter.total) / 60 / 1000;
128                                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
129                                         toQuantityType(kwh, DIGITS_KWH, Units.KILOWATT_HOUR));
130                                 accumulatedTotal += kwh;
131                             }
132                             if (meter.counters != null) {
133                                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
134                                         toQuantityType(getDouble(meter.counters[0]), DIGITS_WATT, Units.WATT));
135                             }
136                             thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
137                                     getTimestamp(getString(profile.settings.timezone), getLong(meter.timestamp)));
138                         }
139                         m++;
140                     }
141                 } else {
142                     for (ShellySettingsEMeter emeter : status.emeters) {
143                         Integer meterIndex = m + 1;
144                         if (getBool(emeter.isValid)) {
145                             String groupName = profile.numMeters > 1 ? CHANNEL_GROUP_METER + meterIndex.toString()
146                                     : CHANNEL_GROUP_METER;
147                             if (!thingHandler.areChannelsCreated()) {
148                                 thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
149                                         .createEMeterChannels(thingHandler.getThing(), emeter, groupName));
150                             }
151
152                             // convert Watt/Hour tok w/h
153                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
154                                     toQuantityType(getDouble(emeter.power), DIGITS_WATT, Units.WATT));
155                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
156                                     toQuantityType(getDouble(emeter.total) / 1000, DIGITS_KWH, Units.KILOWATT_HOUR));
157                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_TOTALRET, toQuantityType(
158                                     getDouble(emeter.totalReturned) / 1000, DIGITS_KWH, Units.KILOWATT_HOUR));
159                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_REACTWATTS,
160                                     toQuantityType(getDouble(emeter.reactive), DIGITS_WATT, Units.WATT));
161                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_VOLTAGE,
162                                     toQuantityType(getDouble(emeter.voltage), DIGITS_VOLT, Units.VOLT));
163                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_CURRENT,
164                                     toQuantityType(getDouble(emeter.current), DIGITS_VOLT, Units.AMPERE));
165                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_PFACTOR,
166                                     toQuantityType(computePF(emeter), Units.PERCENT));
167
168                             accumulatedWatts += getDouble(emeter.power);
169                             accumulatedTotal += getDouble(emeter.total) / 1000;
170                             accumulatedReturned += getDouble(emeter.totalReturned) / 1000;
171                             if (updated) {
172                                 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE, getTimestamp());
173                             }
174                         }
175                         m++;
176                     }
177                 }
178             } else {
179                 // In Roller Mode we accumulate all meters to a single set of meters
180                 thingHandler.logger.trace("{}: Updating Meter (accumulated)", thingHandler.thingName);
181                 double currentWatts = 0.0;
182                 double totalWatts = 0.0;
183                 double lastMin1 = 0.0;
184                 long timestamp = 0l;
185                 String groupName = CHANNEL_GROUP_METER;
186                 for (ShellySettingsMeter meter : status.meters) {
187                     if (meter.isValid) {
188                         currentWatts += getDouble(meter.power);
189                         totalWatts += getDouble(meter.total);
190                         if (meter.counters != null) {
191                             lastMin1 += getDouble(meter.counters[0]);
192                         }
193                         if (getLong(meter.timestamp) > timestamp) {
194                             timestamp = getLong(meter.timestamp); // newest one
195                         }
196                     }
197                 }
198                 // Create channels for 1 Meter
199                 if (!thingHandler.areChannelsCreated()) {
200                     thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
201                             .createMeterChannels(thingHandler.getThing(), status.meters.get(0), groupName));
202                 }
203
204                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
205                         toQuantityType(getDouble(lastMin1), DIGITS_WATT, Units.WATT));
206
207                 // convert totalWatts into kw/h
208                 totalWatts = totalWatts / (60.0 * 1000.0);
209                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
210                         toQuantityType(getDouble(currentWatts), DIGITS_WATT, Units.WATT));
211                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
212                         toQuantityType(getDouble(totalWatts), DIGITS_KWH, Units.KILOWATT_HOUR));
213
214                 if (updated && timestamp > 0) {
215                     thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
216                             getTimestamp(getString(profile.settings.timezone), timestamp));
217                 }
218             }
219
220             if (!profile.isRoller && !profile.isRGBW2) {
221                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUWATTS,
222                         toQuantityType(accumulatedWatts, DIGITS_WATT, Units.WATT));
223                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUTOTAL,
224                         toQuantityType(accumulatedTotal, DIGITS_KWH, Units.KILOWATT_HOUR));
225                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCURETURNED,
226                         toQuantityType(accumulatedReturned, DIGITS_KWH, Units.KILOWATT_HOUR));
227             }
228         }
229
230         return updated;
231     }
232
233     private static Double computePF(ShellySettingsEMeter emeter) {
234         if (emeter.pf != null) { // EM3
235             return emeter.pf; // take device value
236         }
237
238         // EM: compute from provided values
239         if (Math.abs(emeter.power) + Math.abs(emeter.reactive) > 1.5) {
240             double pf = emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive);
241             return pf;
242         }
243         return 0.0;
244     }
245
246     /**
247      * Update Sensor channel
248      *
249      * @param th Thing Handler instance
250      * @param profile ShellyDeviceProfile
251      * @param status Last ShellySettingsStatus
252      *
253      * @throws ShellyApiException
254      */
255     public static boolean updateSensors(ShellyBaseHandler thingHandler, ShellySettingsStatus status)
256             throws ShellyApiException {
257         ShellyDeviceProfile profile = thingHandler.getProfile();
258
259         boolean updated = false;
260         if (profile.isSensor || profile.hasBattery) {
261             ShellyStatusSensor sdata = thingHandler.api.getSensorStatus();
262             if (!thingHandler.areChannelsCreated()) {
263                 thingHandler.logger.trace("{}: Create missing sensor channel(s)", thingHandler.thingName);
264                 thingHandler.updateChannelDefinitions(
265                         ShellyChannelDefinitions.createSensorChannels(thingHandler.getThing(), profile, sdata));
266             }
267
268             updated |= thingHandler.updateWakeupReason(sdata.actReasons);
269
270             if ((sdata.sensor != null) && sdata.sensor.isValid) {
271                 // Shelly DW: “sensor”:{“state”:“open”, “is_valid”:true},
272                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_CONTACT,
273                         getString(sdata.sensor.state).equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
274                                 : OpenClosedType.CLOSED);
275                 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR,
276                         getStringType(sdata.sensorError));
277                 if (changed) {
278                     thingHandler.postEvent(getString(sdata.sensorError), true);
279                 }
280                 updated |= changed;
281             }
282             if ((sdata.tmp != null) && getBool(sdata.tmp.isValid)) {
283                 thingHandler.logger.trace("{}: Updating temperature", thingHandler.thingName);
284                 Double temp = getString(sdata.tmp.units).toUpperCase().equals(SHELLY_TEMP_CELSIUS)
285                         ? getDouble(sdata.tmp.tC)
286                         : getDouble(sdata.tmp.tF);
287                 if (getString(sdata.tmp.units).toUpperCase().equals(SHELLY_TEMP_FAHRENHEIT)) {
288                     // convert Fahrenheit to Celsius
289                     temp = ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(temp).doubleValue();
290                 }
291                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
292                         toQuantityType(temp.doubleValue(), DIGITS_TEMP, SIUnits.CELSIUS));
293             }
294             if (sdata.hum != null) {
295                 thingHandler.logger.trace("{}: Updating humidity", thingHandler.thingName);
296                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_HUM,
297                         toQuantityType(getDouble(sdata.hum.value), DIGITS_PERCENT, Units.PERCENT));
298             }
299             if ((sdata.lux != null) && getBool(sdata.lux.isValid)) {
300                 // “lux”:{“value”:30, “illumination”: “dark”, “is_valid”:true},
301                 thingHandler.logger.trace("{}: Updating lux", thingHandler.thingName);
302                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_LUX,
303                         toQuantityType(getDouble(sdata.lux.value), DIGITS_LUX, Units.LUX));
304                 if (sdata.lux.illumination != null) {
305                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM,
306                             getStringType(sdata.lux.illumination));
307                 }
308             }
309             if (sdata.accel != null) {
310                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
311                         toQuantityType(getDouble(sdata.accel.tilt.doubleValue()), DIGITS_NONE, Units.DEGREE_ANGLE));
312             }
313             if (sdata.flood != null) {
314                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
315                         getOnOff(sdata.flood));
316             }
317             if (sdata.smoke != null) {
318                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SMOKE,
319                         getOnOff(sdata.smoke));
320             }
321             if (sdata.gasSensor != null) {
322                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
323                         getStringType(sdata.gasSensor.selfTestState));
324                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
325                         getStringType(sdata.gasSensor.alarmState));
326                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE,
327                         getStringType(sdata.gasSensor.sensorState));
328             }
329             if ((sdata.concentration != null) && sdata.concentration.isValid) {
330                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM,
331                         getDecimal(sdata.concentration.ppm));
332             }
333             if ((sdata.adcs != null) && (sdata.adcs.size() > 0)) {
334                 ShellyADC adc = sdata.adcs.get(0);
335                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VOLTAGE,
336                         toQuantityType(getDouble(adc.voltage), 2, Units.VOLT));
337             }
338
339             boolean charger = (getInteger(profile.settings.externalPower) == 1) || getBool(sdata.charger);
340             if ((profile.settings.externalPower != null) || (sdata.charger != null)) {
341                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
342                         charger ? OnOffType.ON : OnOffType.OFF);
343             }
344             if (sdata.bat != null) { // no update for Sense
345                 // Shelly HT has external_power under settings, Sense and Motion charger under status
346                 if (!charger || !profile.isHT) {
347                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
348                             toQuantityType(getDouble(sdata.bat.value), 0, Units.PERCENT));
349                 } else {
350                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
351                             UnDefType.UNDEF);
352                 }
353                 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LOW,
354                         getDouble(sdata.bat.value) < thingHandler.config.lowBattery ? OnOffType.ON : OnOffType.OFF);
355                 updated |= changed;
356                 if (changed && getDouble(sdata.bat.value) < thingHandler.config.lowBattery) {
357                     thingHandler.postEvent(ALARM_TYPE_LOW_BATTERY, false);
358                 }
359             }
360
361             if (sdata.motion != null) { // Shelly Sense
362                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
363                         getOnOff(sdata.motion));
364             }
365             if (sdata.sensor != null) { // Shelly Motion
366                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_ACT,
367                         getOnOff(sdata.sensor.motionActive));
368                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
369                         getOnOff(sdata.sensor.motion));
370                 long timestamp = getLong(sdata.sensor.motionTimestamp);
371                 if (timestamp != 0) {
372                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_TS,
373                             getTimestamp(getString(profile.settings.timezone), timestamp));
374                 }
375             }
376
377             updated |= thingHandler.updateInputs(status);
378
379             if (updated) {
380                 thingHandler.updateChannel(profile.getControlGroup(0), CHANNEL_LAST_UPDATE, getTimestamp());
381             }
382         }
383         return updated;
384     }
385 }