2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.handler;
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.*;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.binding.shelly.internal.api.ShellyApiException;
22 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
23 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsEMeter;
24 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsMeter;
25 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
26 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor;
27 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyADC;
28 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
29 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
30 import org.openhab.core.library.types.OnOffType;
31 import org.openhab.core.library.types.OpenClosedType;
32 import org.openhab.core.library.unit.ImperialUnits;
33 import org.openhab.core.library.unit.SIUnits;
34 import org.openhab.core.library.unit.Units;
35 import org.openhab.core.types.UnDefType;
38 * The{@link ShellyComponents} implements updates for supplemental components
39 * Meter will be used by Relay + Light; Sensor is part of H&T, Flood, Door Window, Sense
41 * @author Markus Michels - Initial contribution
44 public class ShellyComponents {
47 * Update device status
49 * @param th Thing Handler instance
50 * @param profile ShellyDeviceProfile
52 public static boolean updateDeviceStatus(ShellyThingInterface thingHandler, ShellySettingsStatus status) {
53 ShellyDeviceProfile profile = thingHandler.getProfile();
55 if (!thingHandler.areChannelsCreated()) {
56 thingHandler.updateChannelDefinitions(ShellyChannelDefinitions.createDeviceChannels(thingHandler.getThing(),
57 thingHandler.getProfile(), status));
60 if (getLong(status.uptime) > 10) {
61 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_UPTIME,
62 toQuantityType((double) getLong(status.uptime), DIGITS_NONE, Units.SECOND));
65 Integer rssi = getInteger(status.wifiSta.rssi);
66 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_RSSI, mapSignalStrength(rssi));
67 if (getDouble(status.temperature) != SHELLY_API_INVTEMP) {
68 if (status.tmp != null && !thingHandler.getProfile().isSensor) {
69 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
70 toQuantityType(getDouble(status.tmp.tC), DIGITS_NONE, SIUnits.CELSIUS));
71 } else if (status.temperature != null) {
72 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
73 toQuantityType(getDouble(status.temperature), DIGITS_NONE, SIUnits.CELSIUS));
76 thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SLEEPTIME,
77 toQuantityType(getInteger(status.sleepTime), Units.SECOND));
79 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_UPDATE, getOnOff(status.hasUpdate));
81 if (profile.settings.calibrated != null) {
82 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CALIBRATED,
83 getOnOff(profile.settings.calibrated));
86 return false; // device status never triggers update
90 * Update Meter channel
92 * @param th Thing Handler instance
93 * @param profile ShellyDeviceProfile
94 * @param status Last ShellySettingsStatus
96 public static boolean updateMeters(ShellyThingInterface thingHandler, ShellySettingsStatus status) {
97 ShellyDeviceProfile profile = thingHandler.getProfile();
99 double accumulatedWatts = 0.0;
100 double accumulatedTotal = 0.0;
101 double accumulatedReturned = 0.0;
103 boolean updated = false;
104 // Devices without power meters get no updates
106 // Roler+RGBW2 have multiple meters -> aggregate consumption to the functional device
107 // Meter and EMeter have a different set of channels
108 if (status.meters != null || status.emeters != null) {
109 if (!profile.isRoller && !profile.isRGBW2) {
110 // In Relay mode we map eacher meter to the matching channel group
112 if (!profile.isEMeter) {
113 for (ShellySettingsMeter meter : status.meters) {
114 if (getBool(meter.isValid) || profile.isLight) { // RGBW2-white doesn't report valid flag
115 // correctly in white mode
116 String groupName = profile.getMeterGroup(m);
117 if (!thingHandler.areChannelsCreated()) {
118 // skip for Shelly Bulb: JSON has a meter, but values don't get updated
119 if (!profile.isBulb) {
120 thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
121 .createMeterChannels(thingHandler.getThing(), meter, groupName));
125 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
126 toQuantityType(getDouble(meter.power), DIGITS_WATT, Units.WATT));
127 accumulatedWatts += getDouble(meter.power);
129 // convert Watt/Min to kw/h
130 if (meter.total != null) {
131 double kwh = getDouble(meter.total) / 60 / 1000;
132 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
133 toQuantityType(kwh, DIGITS_KWH, Units.KILOWATT_HOUR));
134 accumulatedTotal += kwh;
136 if (meter.counters != null) {
137 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
138 toQuantityType(getDouble(meter.counters[0]), DIGITS_WATT, Units.WATT));
140 if (meter.timestamp != null) {
141 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
142 getTimestamp(getString(profile.settings.timezone), meter.timestamp));
148 for (ShellySettingsEMeter emeter : status.emeters) {
149 if (getBool(emeter.isValid)) {
150 String groupName = profile.getMeterGroup(m);
151 if (!thingHandler.areChannelsCreated()) {
152 thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
153 .createEMeterChannels(thingHandler.getThing(), emeter, groupName));
156 // convert Watt/Hour tok w/h
157 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
158 toQuantityType(getDouble(emeter.power), DIGITS_WATT, Units.WATT));
159 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
160 toQuantityType(getDouble(emeter.total) / 1000, DIGITS_KWH, Units.KILOWATT_HOUR));
161 updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_TOTALRET, toQuantityType(
162 getDouble(emeter.totalReturned) / 1000, DIGITS_KWH, Units.KILOWATT_HOUR));
163 updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_REACTWATTS,
164 toQuantityType(getDouble(emeter.reactive), DIGITS_WATT, Units.WATT));
165 updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_VOLTAGE,
166 toQuantityType(getDouble(emeter.voltage), DIGITS_VOLT, Units.VOLT));
167 updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_CURRENT,
168 toQuantityType(getDouble(emeter.current), DIGITS_VOLT, Units.AMPERE));
169 updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_PFACTOR,
170 toQuantityType(computePF(emeter), Units.PERCENT));
172 accumulatedWatts += getDouble(emeter.power);
173 accumulatedTotal += getDouble(emeter.total) / 1000;
174 accumulatedReturned += getDouble(emeter.totalReturned) / 1000;
176 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE, getTimestamp());
183 // In Roller Mode we accumulate all meters to a single set of meters
184 double currentWatts = 0.0;
185 double totalWatts = 0.0;
186 double lastMin1 = 0.0;
188 String groupName = CHANNEL_GROUP_METER;
190 if (!thingHandler.areChannelsCreated()) {
191 ShellySettingsMeter m = status.meters.get(0);
192 if (getBool(m.isValid)) {
193 // Create channels for 1 Meter
194 thingHandler.updateChannelDefinitions(
195 ShellyChannelDefinitions.createMeterChannels(thingHandler.getThing(), m, groupName));
199 for (ShellySettingsMeter meter : status.meters) {
200 if (getBool(meter.isValid)) {
201 currentWatts += getDouble(meter.power);
202 totalWatts += getDouble(meter.total);
203 if (meter.counters != null) {
204 lastMin1 += getDouble(meter.counters[0]);
206 if (getLong(meter.timestamp) > timestamp) {
207 timestamp = getLong(meter.timestamp); // newest one
212 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
213 toQuantityType(getDouble(lastMin1), DIGITS_WATT, Units.WATT));
215 // convert totalWatts into kw/h
216 totalWatts = totalWatts / (60.0 * 1000.0);
217 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
218 toQuantityType(getDouble(currentWatts), DIGITS_WATT, Units.WATT));
219 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
220 toQuantityType(getDouble(totalWatts), DIGITS_KWH, Units.KILOWATT_HOUR));
222 if (updated && timestamp > 0) {
223 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
224 getTimestamp(getString(profile.settings.timezone), timestamp));
228 if (!profile.isRoller && !profile.isRGBW2) {
229 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUWATTS,
230 toQuantityType(accumulatedWatts, DIGITS_WATT, Units.WATT));
231 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUTOTAL,
232 toQuantityType(accumulatedTotal, DIGITS_KWH, Units.KILOWATT_HOUR));
233 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCURETURNED,
234 toQuantityType(accumulatedReturned, DIGITS_KWH, Units.KILOWATT_HOUR));
241 private static Double computePF(ShellySettingsEMeter emeter) {
242 if (emeter.pf != null) { // EM3
243 return emeter.pf; // take device value
246 // EM: compute from provided values
247 if (emeter.reactive != null && Math.abs(emeter.power) + Math.abs(emeter.reactive) > 1.5) {
248 double pf = emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive);
255 * Update Sensor channel
257 * @param th Thing Handler instance
258 * @param profile ShellyDeviceProfile
259 * @param status Last ShellySettingsStatus
261 * @throws ShellyApiException
263 public static boolean updateSensors(ShellyThingInterface thingHandler, ShellySettingsStatus status)
264 throws ShellyApiException {
265 ShellyDeviceProfile profile = thingHandler.getProfile();
267 boolean updated = false;
268 if (profile.isSensor || profile.hasBattery) {
269 ShellyStatusSensor sdata = thingHandler.getApi().getSensorStatus();
270 if (!thingHandler.areChannelsCreated()) {
271 thingHandler.updateChannelDefinitions(
272 ShellyChannelDefinitions.createSensorChannels(thingHandler.getThing(), profile, sdata));
275 updated |= thingHandler.updateWakeupReason(sdata.actReasons);
277 if ((sdata.sensor != null) && sdata.sensor.isValid) {
278 // Shelly DW: “sensor”:{“state”:“open”, “is_valid”:true},
279 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
280 getString(sdata.sensor.state).equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
281 : OpenClosedType.CLOSED);
282 String sensorError = sdata.sensorError;
283 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR,
284 getStringType(sensorError));
285 if (changed && !"0".equals(sensorError)) {
286 thingHandler.postEvent(getString(sdata.sensorError), true);
290 if ((sdata.tmp != null) && getBool(sdata.tmp.isValid)) {
291 Double temp = getString(sdata.tmp.units).toUpperCase().equals(SHELLY_TEMP_CELSIUS)
292 ? getDouble(sdata.tmp.tC)
293 : getDouble(sdata.tmp.tF);
294 if (getString(sdata.tmp.units).toUpperCase().equals(SHELLY_TEMP_FAHRENHEIT)) {
295 // convert Fahrenheit to Celsius
296 temp = ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(temp).doubleValue();
298 temp = convertToC(temp, getString(sdata.tmp.units));
299 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
300 toQuantityType(temp.doubleValue(), DIGITS_TEMP, SIUnits.CELSIUS));
301 } else if (status.thermostats != null && profile.settings.thermostats != null) {
303 ShellyThermnostat t = status.thermostats.get(0);
304 ShellyThermnostat ps = profile.settings.thermostats.get(0);
305 int bminutes = getInteger(t.boostMinutes) > 0 ? getInteger(t.boostMinutes)
306 : getInteger(ps.boostMinutes);
307 updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BCONTROL,
308 getOnOff(getInteger(t.boostMinutes) > 0));
309 updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BTIMER,
310 toQuantityType((double) bminutes, DIGITS_NONE, Units.MINUTE));
311 updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_MODE,
312 getStringType(getBool(t.targetTemp.enabled) ? SHELLY_TRV_MODE_AUTO : SHELLY_TRV_MODE_MANUAL));
313 updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE,
314 getDecimal(getBool(t.schedule) ? t.profile + 1 : 0));
315 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SCHEDULE,
316 getOnOff(t.schedule));
318 Double temp = convertToC(t.tmp.value, getString(t.tmp.units));
319 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
320 toQuantityType(temp.doubleValue(), DIGITS_TEMP, SIUnits.CELSIUS));
321 temp = convertToC(t.targetTemp.value, getString(t.targetTemp.unit));
322 updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_SETTEMP,
323 toQuantityType(t.targetTemp.value, DIGITS_TEMP, SIUnits.CELSIUS));
326 updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_POSITION,
327 t.pos != -1 ? toQuantityType(t.pos, DIGITS_NONE, Units.PERCENT) : UnDefType.UNDEF);
328 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
329 getDouble(t.pos) > 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
333 if (sdata.hum != null) {
334 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_HUM,
335 toQuantityType(getDouble(sdata.hum.value), DIGITS_PERCENT, Units.PERCENT));
337 if ((sdata.lux != null) && getBool(sdata.lux.isValid)) {
338 // “lux”:{“value”:30, “illumination”: “dark”, “is_valid”:true},
339 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_LUX,
340 toQuantityType(getDouble(sdata.lux.value), DIGITS_LUX, Units.LUX));
341 if (sdata.lux.illumination != null) {
342 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM,
343 getStringType(sdata.lux.illumination));
346 if (sdata.accel != null) {
347 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
348 toQuantityType(getDouble(sdata.accel.tilt.doubleValue()), DIGITS_NONE, Units.DEGREE_ANGLE));
350 if (sdata.flood != null) {
351 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
352 getOnOff(sdata.flood));
354 if (sdata.smoke != null) {
355 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SMOKE,
356 getOnOff(sdata.smoke));
358 if (sdata.gasSensor != null) {
359 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
360 getStringType(sdata.gasSensor.selfTestState));
361 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
362 getStringType(sdata.gasSensor.alarmState));
363 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE,
364 getStringType(sdata.gasSensor.sensorState));
366 if ((sdata.concentration != null) && sdata.concentration.isValid) {
367 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, toQuantityType(
368 getInteger(sdata.concentration.ppm).doubleValue(), DIGITS_NONE, Units.PARTS_PER_MILLION));
370 if ((sdata.adcs != null) && (sdata.adcs.size() > 0)) {
371 ShellyADC adc = sdata.adcs.get(0);
372 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VOLTAGE,
373 toQuantityType(getDouble(adc.voltage), 2, Units.VOLT));
376 boolean charger = (getInteger(profile.settings.externalPower) == 1) || getBool(sdata.charger);
377 if ((profile.settings.externalPower != null) || (sdata.charger != null)) {
378 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
379 charger ? OnOffType.ON : OnOffType.OFF);
381 if (sdata.bat != null) { // no update for Sense
382 updated |= thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
383 toQuantityType(getDouble(sdata.bat.value), 0, Units.PERCENT));
385 int lowBattery = thingHandler.getThingConfig().lowBattery;
386 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LOW,
387 !charger && getDouble(sdata.bat.value) < lowBattery ? OnOffType.ON : OnOffType.OFF);
389 if (!charger && changed && getDouble(sdata.bat.value) < lowBattery) {
390 thingHandler.postEvent(ALARM_TYPE_LOW_BATTERY, false);
394 if (sdata.motion != null) { // Shelly Sense
395 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
396 getOnOff(sdata.motion));
398 if (sdata.sensor != null) { // Shelly Motion
399 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_ACT,
400 getOnOff(sdata.sensor.motionActive));
401 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
402 getOnOff(sdata.sensor.motion));
403 long timestamp = getLong(sdata.sensor.motionTimestamp);
404 if (timestamp != 0) {
405 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_TS,
406 getTimestamp(getString(profile.settings.timezone), timestamp));
410 updated |= thingHandler.updateInputs(status);
413 thingHandler.updateChannel(profile.getControlGroup(0), CHANNEL_LAST_UPDATE, getTimestamp());
419 private static Double convertToC(@Nullable Double temp, String unit) {
423 if (SHELLY_TEMP_FAHRENHEIT.equalsIgnoreCase(unit)) {
424 // convert Fahrenheit to Celsius
425 return ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(temp).doubleValue();