]> git.basschouten.com Git - openhab-addons.git/blob
1d5a0cc133234c59105971ed33a68b8e4f44df0b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18
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;
24 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyRollerStatus;
25 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDimmer;
26 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsEMeter;
27 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsMeter;
28 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
29 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
30 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
31 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor;
32 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyADC;
33 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtTemperature.ShellyShortTemp;
34 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
35 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
36 import org.openhab.core.library.types.OnOffType;
37 import org.openhab.core.library.types.StringType;
38 import org.openhab.core.library.unit.ImperialUnits;
39 import org.openhab.core.library.unit.SIUnits;
40 import org.openhab.core.library.unit.Units;
41 import org.openhab.core.types.UnDefType;
42
43 import com.google.gson.Gson;
44
45 /***
46  * The{@link ShellyComponents} implements updates for supplemental components
47  * Meter will be used by Relay + Light; Sensor is part of H&T, Flood, Door Window, Sense
48  *
49  * @author Markus Michels - Initial contribution
50  */
51 @NonNullByDefault
52 public class ShellyComponents {
53
54     /**
55      * Update device status
56      *
57      * @param thingHandler Thing Handler instance
58      * @param status Status message
59      */
60     public static boolean updateDeviceStatus(ShellyThingInterface thingHandler, ShellySettingsStatus status) {
61         ShellyDeviceProfile profile = thingHandler.getProfile();
62
63         if (!profile.gateway.isEmpty()) {
64             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_GATEWAY, getStringType(profile.gateway));
65         }
66         if (!thingHandler.areChannelsCreated()) {
67             thingHandler.updateChannelDefinitions(ShellyChannelDefinitions.createDeviceChannels(thingHandler.getThing(),
68                     thingHandler.getProfile(), status));
69         }
70
71         if (getLong(status.uptime) > 10) {
72             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_UPTIME,
73                     toQuantityType((double) getLong(status.uptime), DIGITS_NONE, Units.SECOND));
74         }
75
76         Integer rssi = getInteger(status.wifiSta.rssi);
77         thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_RSSI, mapSignalStrength(rssi));
78         if (status.tmp != null && getBool(status.tmp.isValid) && !thingHandler.getProfile().isSensor
79                 && status.tmp.tC != SHELLY_API_INVTEMP) {
80             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
81                     toQuantityType(getDouble(status.tmp.tC), DIGITS_TEMP, SIUnits.CELSIUS));
82         } else if (status.temperature != null && status.temperature != SHELLY_API_INVTEMP) {
83             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
84                     toQuantityType(getDouble(status.temperature), DIGITS_NONE, SIUnits.CELSIUS));
85         }
86         thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SLEEPTIME,
87                 toQuantityType(getInteger(status.sleepTime), Units.SECOND));
88
89         thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_UPDATE, getOnOff(status.hasUpdate));
90
91         if (profile.settings.calibrated != null) {
92             thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CALIBRATED,
93                     getOnOff(profile.settings.calibrated));
94         }
95
96         return false; // device status never triggers update
97     }
98
99     public static boolean updateRelay(ShellyBaseHandler thingHandler, ShellySettingsStatus status, int id) {
100         ShellyDeviceProfile profile = thingHandler.getProfile();
101         ShellySettingsRelay relay = status.relays.get(id);
102         ShellySettingsRelay rsettings;
103         if (profile.settings.relays != null) {
104             rsettings = profile.settings.relays.get(id);
105         } else {
106             throw new IllegalArgumentException("No relay settings");
107         }
108
109         boolean updated = false;
110         if (relay.isValid == null || relay.isValid) {
111             String groupName = profile.getControlGroup(id);
112             updated |= thingHandler.updateChannel(groupName, CHANNEL_OUTPUT_NAME, getStringType(rsettings.name));
113
114             if (getBool(relay.overpower)) {
115                 thingHandler.postEvent(ALARM_TYPE_OVERPOWER, false);
116             }
117
118             updated |= thingHandler.updateChannel(groupName, CHANNEL_OUTPUT, getOnOff(relay.ison));
119             updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_ACTIVE, getOnOff(relay.hasTimer));
120             if (status.extSwitch != null) {
121                 if (status.extSwitch.input0 != null) {
122                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_ESENSOR_INPUT1,
123                             getOpenClosed(getInteger(status.extSwitch.input0.input) == 1));
124                 }
125             }
126             if (status.extTemperature != null) {
127                 // Shelly 1/1PM support up to 3 external sensors
128                 // for whatever reason those are not represented as an array, but 3 elements
129                 updated |= updateTempChannel(status.extTemperature.sensor1, thingHandler, CHANNEL_ESENSOR_TEMP1);
130                 updated |= updateTempChannel(status.extTemperature.sensor2, thingHandler, CHANNEL_ESENSOR_TEMP2);
131                 updated |= updateTempChannel(status.extTemperature.sensor3, thingHandler, CHANNEL_ESENSOR_TEMP3);
132                 updated |= updateTempChannel(status.extTemperature.sensor4, thingHandler, CHANNEL_ESENSOR_TEMP4);
133                 updated |= updateTempChannel(status.extTemperature.sensor5, thingHandler, CHANNEL_ESENSOR_TEMP5);
134             }
135             if ((status.extHumidity != null) && (status.extHumidity.sensor1 != null)) {
136                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_ESENSOR_HUMIDITY,
137                         toQuantityType(getDouble(status.extHumidity.sensor1.hum), DIGITS_PERCENT, Units.PERCENT));
138             }
139             if ((status.extVoltage != null) && (status.extVoltage.sensor1 != null)) {
140                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_ESENSOR_VOLTAGE,
141                         toQuantityType(getDouble(status.extVoltage.sensor1.voltage), 4, Units.VOLT));
142             }
143             if ((status.extDigitalInput != null) && (status.extDigitalInput.sensor1 != null)) {
144                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_ESENSOR_DIGITALINPUT,
145                         getOnOff(status.extDigitalInput.sensor1.state));
146             }
147             if ((status.extAnalogInput != null) && (status.extAnalogInput.sensor1 != null)) {
148                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_ESENSOR_ANALOGINPUT, toQuantityType(
149                         getDouble(status.extAnalogInput.sensor1.percent), DIGITS_PERCENT, Units.PERCENT));
150             }
151
152             // Update Auto-ON/OFF timer
153             updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_AUTOON,
154                     toQuantityType(getDouble(rsettings.autoOn), Units.SECOND));
155             updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_AUTOOFF,
156                     toQuantityType(getDouble(rsettings.autoOff), Units.SECOND));
157         }
158         return updated;
159     }
160
161     public static boolean updateRoller(ShellyBaseHandler thingHandler, ShellyRollerStatus control, int id)
162             throws ShellyApiException {
163         ShellyDeviceProfile profile = thingHandler.getProfile();
164         boolean updated = false;
165         if (getBool(control.isValid)) {
166             String groupName = profile.getControlGroup(id);
167             if (control.name != null) {
168                 updated |= thingHandler.updateChannel(groupName, CHANNEL_OUTPUT_NAME, getStringType(control.name));
169             }
170
171             String state = getString(control.state);
172             int pos = -1;
173             switch (state) {
174                 case SHELLY_ALWD_ROLLER_TURN_OPEN:
175                     pos = SHELLY_MAX_ROLLER_POS;
176                     break;
177                 case SHELLY_ALWD_ROLLER_TURN_CLOSE:
178                     pos = SHELLY_MIN_ROLLER_POS;
179                     break;
180                 case SHELLY_ALWD_ROLLER_TURN_STOP:
181                     if (control.currentPos != null) {
182                         // only valid in stop state
183                         pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min(control.currentPos, SHELLY_MAX_ROLLER_POS));
184                     }
185                     break;
186             }
187             if (pos != -1) {
188                 thingHandler.logger.debug("{}: Update roller position to {}/{}, state={}", thingHandler.thingName, pos,
189                         SHELLY_MAX_ROLLER_POS - pos, state);
190                 updated |= thingHandler.updateChannel(groupName, CHANNEL_ROL_CONTROL_CONTROL,
191                         toQuantityType((double) (SHELLY_MAX_ROLLER_POS - pos), Units.PERCENT));
192                 updated |= thingHandler.updateChannel(groupName, CHANNEL_ROL_CONTROL_POS,
193                         toQuantityType((double) pos, Units.PERCENT));
194             }
195
196             updated |= thingHandler.updateChannel(groupName, CHANNEL_ROL_CONTROL_STATE, new StringType(state));
197             updated |= thingHandler.updateChannel(groupName, CHANNEL_ROL_CONTROL_STOPR,
198                     getStringType(control.stopReason));
199             updated |= thingHandler.updateChannel(groupName, CHANNEL_ROL_CONTROL_SAFETY,
200                     getOnOff(control.safetySwitch));
201         }
202         return updated;
203     }
204
205     /**
206      * Update Meter channel
207      *
208      * @param thingHandler Thing Handler instance
209      * @param status Last ShellySettingsStatus
210      */
211     public static boolean updateMeters(ShellyThingInterface thingHandler, ShellySettingsStatus status) {
212         ShellyDeviceProfile profile = thingHandler.getProfile();
213
214         double accumulatedWatts = 0.0;
215         double accumulatedTotal = 0.0;
216         double accumulatedReturned = 0.0;
217
218         boolean updated = false;
219         // Devices without power meters get no updates
220         // We need to differ
221         // Roler+RGBW2 have multiple meters -> aggregate consumption to the functional device
222         // Meter and EMeter have a different set of channels
223         if (status.meters != null || status.emeters != null) {
224             if (!profile.isRoller && !profile.isRGBW2) {
225                 // In Relay mode we map eacher meter to the matching channel group
226                 int m = 0;
227                 if (!profile.isEMeter) {
228                     for (ShellySettingsMeter meter : status.meters) {
229                         if (m >= profile.numMeters) {
230                             // Shelly1: reports status.meters[0].is_valid = true, but even doesn't have a meter
231                             meter.isValid = false;
232                         }
233                         if (getBool(meter.isValid) || profile.isLight) { // RGBW2-white doesn't report valid flag
234                             // correctly in white mode
235                             String groupName = profile.getMeterGroup(m);
236                             if (!thingHandler.areChannelsCreated()) {
237                                 // skip for Shelly Bulb: JSON has a meter, but values don't get updated
238                                 if (!profile.isBulb) {
239                                     thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
240                                             .createMeterChannels(thingHandler.getThing(), meter, groupName));
241                                 }
242                             }
243
244                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
245                                     toQuantityType(getDouble(meter.power), DIGITS_WATT, Units.WATT));
246                             accumulatedWatts += getDouble(meter.power);
247
248                             // convert Watt/Min to kw/h
249                             if (meter.total != null) {
250                                 double kwh = getDouble(meter.total) / 1000 / 60;
251                                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
252                                         toQuantityType(kwh, DIGITS_KWH, Units.KILOWATT_HOUR));
253                                 accumulatedTotal += kwh;
254                             }
255                             if (meter.counters != null) {
256                                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
257                                         toQuantityType(getDouble(meter.counters[0]), DIGITS_WATT, Units.WATT));
258                             }
259                             if (meter.timestamp != null) {
260                                 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
261                                         getTimestamp(getString(profile.settings.timezone), meter.timestamp));
262                             }
263                         }
264                         m++;
265                     }
266                 } else {
267                     if (status.neutralCurrent != null) {
268                         if (!thingHandler.areChannelsCreated()) {
269                             thingHandler.updateChannelDefinitions(ShellyChannelDefinitions.createEMNCurrentChannels(
270                                     thingHandler.getThing(), profile.settings.neutralCurrent, status.neutralCurrent));
271                         }
272                         if (getBool(status.neutralCurrent.isValid)) {
273                             String ngroup = CHANNEL_GROUP_NMETER;
274                             updated |= thingHandler.updateChannel(ngroup, CHANNEL_NMETER_CURRENT, toQuantityType(
275                                     getDouble(status.neutralCurrent.current), DIGITS_AMPERE, Units.AMPERE));
276                             updated |= thingHandler.updateChannel(ngroup, CHANNEL_NMETER_IXSUM, toQuantityType(
277                                     getDouble(status.neutralCurrent.ixsum), DIGITS_AMPERE, Units.AMPERE));
278                             updated |= thingHandler.updateChannel(ngroup, CHANNEL_NMETER_MTRESHHOLD,
279                                     toQuantityType(getDouble(profile.settings.neutralCurrent.mismatchThreshold),
280                                             DIGITS_AMPERE, Units.AMPERE));
281                             updated |= thingHandler.updateChannel(ngroup, CHANNEL_NMETER_MISMATCH,
282                                     getOnOff(status.neutralCurrent.mismatch));
283                         }
284                     }
285
286                     for (ShellySettingsEMeter emeter : status.emeters) {
287                         if (getBool(emeter.isValid)) {
288                             String groupName = profile.getMeterGroup(m);
289                             if (!thingHandler.areChannelsCreated()) {
290                                 thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
291                                         .createEMeterChannels(thingHandler.getThing(), profile, emeter, groupName));
292                             }
293
294                             // convert Watt/h to KW/h
295                             double total = getDouble(emeter.total) / 1000;
296                             double totalReturned = getDouble(emeter.totalReturned) / 1000;
297                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
298                                     toQuantityType(getDouble(emeter.power), DIGITS_WATT, Units.WATT));
299                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
300                                     toQuantityType(total, DIGITS_KWH, Units.KILOWATT_HOUR));
301                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_TOTALRET,
302                                     toQuantityType(totalReturned, DIGITS_KWH, Units.KILOWATT_HOUR));
303                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_REACTWATTS,
304                                     toQuantityType(getDouble(emeter.reactive), DIGITS_WATT, Units.WATT));
305                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_VOLTAGE,
306                                     toQuantityType(getDouble(emeter.voltage), DIGITS_VOLT, Units.VOLT));
307                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_CURRENT,
308                                     toQuantityType(getDouble(emeter.current), DIGITS_AMPERE, Units.AMPERE));
309                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_PFACTOR,
310                                     toQuantityType(computePF(emeter), Units.PERCENT));
311
312                             accumulatedWatts += getDouble(emeter.power);
313                             accumulatedTotal += total;
314                             accumulatedReturned += totalReturned;
315                             if (updated) {
316                                 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE, getTimestamp());
317                             }
318                         }
319                         m++;
320                     }
321                 }
322             } else {
323                 // In Roller Mode we accumulate all meters to a single set of meters
324                 double currentWatts = 0.0;
325                 double totalWatts = 0.0;
326                 double lastMin1 = 0.0;
327                 long timestamp = 0l;
328                 String groupName = CHANNEL_GROUP_METER;
329
330                 if (!thingHandler.areChannelsCreated()) {
331                     ShellySettingsMeter m = status.meters.get(0);
332                     if (getBool(m.isValid)) {
333                         // Create channels for 1 Meter
334                         thingHandler.updateChannelDefinitions(
335                                 ShellyChannelDefinitions.createMeterChannels(thingHandler.getThing(), m, groupName));
336                     }
337                 }
338
339                 for (ShellySettingsMeter meter : status.meters) {
340                     if (getBool(meter.isValid)) {
341                         currentWatts += getDouble(meter.power);
342                         totalWatts += getDouble(meter.total);
343                         if (meter.counters != null) {
344                             lastMin1 += getDouble(meter.counters[0]);
345                         }
346                         if (getLong(meter.timestamp) > timestamp) {
347                             timestamp = getLong(meter.timestamp); // newest one
348                         }
349                     }
350                 }
351
352                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
353                         toQuantityType(getDouble(lastMin1), DIGITS_WATT, Units.WATT));
354
355                 // convert totalWatts into kw/h
356                 totalWatts = totalWatts / (60.0 * 1000.0);
357                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
358                         toQuantityType(currentWatts, DIGITS_WATT, Units.WATT));
359                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
360                         toQuantityType(totalWatts, DIGITS_KWH, Units.KILOWATT_HOUR));
361
362                 if (updated && timestamp > 0) {
363                     thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
364                             getTimestamp(getString(profile.settings.timezone), timestamp));
365                 }
366             }
367
368             if (!profile.isRoller && !profile.isRGBW2) {
369                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUWATTS, toQuantityType(
370                         status.totalPower != null ? status.totalPower : accumulatedWatts, DIGITS_WATT, Units.WATT));
371                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUTOTAL,
372                         toQuantityType(status.totalCurrent != null ? status.totalCurrent / 1000 : accumulatedTotal,
373                                 DIGITS_KWH, Units.KILOWATT_HOUR));
374                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCURETURNED,
375                         toQuantityType(status.totalReturned != null ? status.totalReturned / 1000 : accumulatedReturned,
376                                 DIGITS_KWH, Units.KILOWATT_HOUR));
377             }
378         }
379
380         return updated;
381     }
382
383     private static Double computePF(ShellySettingsEMeter emeter) {
384         if (emeter.pf != null) { // EM3
385             return emeter.pf; // take device value
386         }
387
388         // EM: compute from provided values
389         if (emeter.reactive != null && Math.abs(emeter.power) + Math.abs(emeter.reactive) > 1.5) {
390             return emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive);
391         }
392         return 0.0;
393     }
394
395     /**
396      * Update Sensor channel
397      *
398      * @param thingHandler Thing Handler instance
399      * @param status Last ShellySettingsStatus
400      *
401      * @throws ShellyApiException
402      */
403     public static boolean updateSensors(ShellyThingInterface thingHandler, ShellySettingsStatus status)
404             throws ShellyApiException {
405         ShellyDeviceProfile profile = thingHandler.getProfile();
406
407         boolean updated = false;
408         if (profile.isSensor || profile.hasBattery) {
409             ShellyStatusSensor sdata = thingHandler.getApi().getSensorStatus();
410             if (!thingHandler.areChannelsCreated()) {
411                 thingHandler.updateChannelDefinitions(
412                         ShellyChannelDefinitions.createSensorChannels(thingHandler.getThing(), profile, sdata));
413             }
414
415             updated |= thingHandler.updateWakeupReason(sdata.actReasons);
416
417             if ((sdata.sensor != null) && sdata.sensor.isValid) {
418                 // Shelly DW: “sensor”:{“state”:“open”, “is_valid”:true},
419                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
420                         getOpenClosed(getString(sdata.sensor.state).equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN)));
421                 String sensorError = sdata.sensorError;
422                 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR,
423                         getStringType(sensorError));
424                 if (changed && !"0".equals(sensorError)) {
425                     thingHandler.postEvent(getString(sdata.sensorError), true);
426                 }
427                 updated |= changed;
428             }
429             if (sdata.tmp != null && getBool(sdata.tmp.isValid)) {
430                 Double temp = getString(sdata.tmp.units).toUpperCase().equals(SHELLY_TEMP_CELSIUS)
431                         ? getDouble(sdata.tmp.tC)
432                         : getDouble(sdata.tmp.tF);
433                 updated |= updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
434                         temp.doubleValue(), getString(sdata.tmp.units));
435             } else if (status.thermostats != null) {
436                 // Shelly TRV
437                 if (profile.settings.thermostats != null) {
438                     ShellyThermnostat ps = profile.settings.thermostats.get(0);
439                     ShellyThermnostat t = status.thermostats.get(0);
440                     int bminutes = getInteger(t.boostMinutes) >= 0 ? getInteger(t.boostMinutes)
441                             : getInteger(ps.boostMinutes);
442                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BCONTROL,
443                             getOnOff(getInteger(t.boostMinutes) > 0));
444                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BTIMER,
445                             toQuantityType((double) bminutes, DIGITS_NONE, Units.MINUTE));
446                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_MODE, getStringType(
447                             getBool(t.targetTemp.enabled) ? SHELLY_TRV_MODE_AUTO : SHELLY_TRV_MODE_MANUAL));
448
449                     int pid = getBool(t.schedule) ? getInteger(t.profile) : 0;
450                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_SCHEDULE,
451                             getOnOff(t.schedule));
452                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE,
453                             getStringType(profile.getValueProfile(0, pid)));
454                     if (t.tmp != null) {
455                         updated |= updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
456                                 t.tmp.value, t.tmp.units);
457                         if (t.targetTemp.unit == null) {
458                             t.targetTemp.unit = t.tmp.units;
459                         }
460                         updated |= updateTempChannel(thingHandler, CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_SETTEMP,
461                                 t.targetTemp.value, t.targetTemp.unit);
462                     }
463                     if (t.pos != null) {
464                         updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_POSITION,
465                                 t.pos != -1 ? toQuantityType(t.pos, DIGITS_NONE, Units.PERCENT) : UnDefType.UNDEF);
466                         updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
467                                 getOpenClosed(getDouble(t.pos) > 0));
468                     }
469                 }
470             }
471
472             if (sdata.hum != null) {
473                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_HUM,
474                         toQuantityType(getDouble(sdata.hum.value), DIGITS_PERCENT, Units.PERCENT));
475             }
476             if ((sdata.lux != null) && getBool(sdata.lux.isValid)) {
477                 // “lux”:{“value”:30, “illumination”: “dark”, “is_valid”:true},
478                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_LUX,
479                         toQuantityType(getDouble(sdata.lux.value), DIGITS_LUX, Units.LUX));
480                 if (sdata.lux.illumination != null) {
481                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM,
482                             getStringType(sdata.lux.illumination));
483                 }
484             }
485             if (sdata.accel != null) {
486                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
487                         toQuantityType(getDouble(sdata.accel.tilt.doubleValue()), DIGITS_NONE, Units.DEGREE_ANGLE));
488             }
489             if (sdata.flood != null) {
490                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
491                         getOnOff(sdata.flood));
492             }
493             if (sdata.smoke != null) {
494                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SMOKE,
495                         getOnOff(sdata.smoke));
496             }
497             if (sdata.mute != null) {
498                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MUTE, getOnOff(sdata.mute));
499             }
500
501             if (sdata.gasSensor != null) {
502                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
503                         getStringType(sdata.gasSensor.selfTestState));
504                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
505                         getStringType(sdata.gasSensor.alarmState));
506                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE,
507                         getStringType(sdata.gasSensor.sensorState));
508             }
509             if ((sdata.concentration != null) && sdata.concentration.isValid) {
510                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, toQuantityType(
511                         getInteger(sdata.concentration.ppm).doubleValue(), DIGITS_NONE, Units.PARTS_PER_MILLION));
512             }
513             if ((sdata.adcs != null) && (!sdata.adcs.isEmpty())) {
514                 ShellyADC adc = sdata.adcs.get(0);
515                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VOLTAGE,
516                         toQuantityType(getDouble(adc.voltage), 2, Units.VOLT));
517             }
518
519             boolean charger = (getInteger(profile.settings.externalPower) == 1) || getBool(sdata.charger);
520             if ((profile.settings.externalPower != null) || (sdata.charger != null)) {
521                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
522                         getOnOff(charger));
523             }
524             if (sdata.bat != null) { // no update for Sense
525                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
526                         toQuantityType(getDouble(sdata.bat.value), 0, Units.PERCENT));
527
528                 int lowBattery = thingHandler.getThingConfig().lowBattery;
529                 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LOW,
530                         getOnOff(!charger && getDouble(sdata.bat.value) < lowBattery));
531                 updated |= changed;
532                 if (!charger && changed && getDouble(sdata.bat.value) < lowBattery) {
533                     thingHandler.postEvent(ALARM_TYPE_LOW_BATTERY, false);
534                 }
535             }
536
537             if (sdata.motion != null) { // Shelly Sense
538                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
539                         getOnOff(sdata.motion));
540             }
541             if (sdata.sensor != null) { // Shelly Motion
542                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_ACT,
543                         getOnOff(sdata.sensor.motionActive));
544                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
545                         getOnOff(sdata.sensor.motion));
546                 long timestamp = getLong(sdata.sensor.motionTimestamp);
547                 if (timestamp != 0) {
548                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_TS,
549                             getTimestamp(getString(profile.settings.timezone), timestamp));
550                 }
551             }
552
553             updated |= thingHandler.updateInputs(status);
554
555             if (updated) {
556                 thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_LAST_UPDATE, getTimestamp());
557             }
558         }
559         return updated;
560     }
561
562     public static boolean updateDimmers(ShellyThingInterface thingHandler, ShellySettingsStatus orgStatus)
563             throws ShellyApiException {
564         boolean updated = false;
565         ShellyDeviceProfile profile = thingHandler.getProfile();
566         if (profile.isDimmer) {
567             // We need to fixup the returned Json: The dimmer returns light[] element, which is ok, but it doesn't have
568             // the same structure as lights[] from Bulb,RGBW2 and Duo. The tag gets replaced by dimmers[] so that Gson
569             // maps to a different structure (ShellyShortLight).
570             Gson gson = new Gson();
571             ShellySettingsStatus dstatus = !profile.isGen2
572                     ? fromJson(gson, Shelly1ApiJsonDTO.fixDimmerJson(orgStatus.json), ShellySettingsStatus.class)
573                     : orgStatus;
574
575             int l = 0;
576             for (ShellyShortLightStatus dimmer : dstatus.dimmers) {
577                 Integer r = l + 1;
578                 String groupName = profile.numRelays <= 1 ? CHANNEL_GROUP_DIMMER_CONTROL
579                         : CHANNEL_GROUP_DIMMER_CONTROL + r.toString();
580
581                 if (!thingHandler.areChannelsCreated()) {
582                     thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
583                             .createDimmerChannels(thingHandler.getThing(), profile, dstatus, l));
584                 }
585
586                 ShellySettingsDimmer ds = profile.settings.dimmers.get(l);
587                 if (ds.name != null) {
588                     updated |= thingHandler.updateChannel(groupName, CHANNEL_OUTPUT_NAME, getStringType(ds.name));
589                 }
590
591                 // On a status update we map a dimmer.ison = false to brightness 0 rather than the device's brightness
592                 // and send an OFF status to the same channel.
593                 // When the device's brightness is > 0 we send the new value to the channel and an ON command
594                 if (dimmer.ison) {
595                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Switch", OnOffType.ON);
596                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Value",
597                             toQuantityType((double) getInteger(dimmer.brightness), DIGITS_NONE, Units.PERCENT));
598                 } else {
599                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Switch", OnOffType.OFF);
600                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Value",
601                             toQuantityType(0.0, DIGITS_NONE, Units.PERCENT));
602                 }
603
604                 if (profile.settings.dimmers != null) {
605                     ShellySettingsDimmer dsettings = profile.settings.dimmers.get(l);
606                     if (dsettings != null) {
607                         updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_AUTOON,
608                                 toQuantityType(getDouble(dsettings.autoOn), Units.SECOND));
609                         updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_AUTOOFF,
610                                 toQuantityType(getDouble(dsettings.autoOff), Units.SECOND));
611                     }
612                 }
613
614                 l++;
615             }
616         }
617         return updated;
618     }
619
620     public static boolean updateTempChannel(@Nullable ShellyShortTemp sensor, ShellyThingInterface thingHandler,
621             String channel) {
622         return sensor != null ? updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, channel, sensor.tC, "") : false;
623     }
624
625     public static boolean updateTempChannel(ShellyThingInterface thingHandler, String group, String channel,
626             @Nullable Double temp, @Nullable String unit) {
627         if (temp == null || temp == SHELLY_API_INVTEMP) {
628             return false;
629         }
630         return thingHandler.updateChannel(group, channel,
631                 toQuantityType(convertToC(temp, unit), DIGITS_TEMP, SIUnits.CELSIUS));
632     }
633
634     private static Double convertToC(@Nullable Double temp, @Nullable String unit) {
635         if (temp == null || temp == SHELLY_API_INVTEMP) {
636             return SHELLY_API_INVTEMP;
637         }
638         if (SHELLY_TEMP_FAHRENHEIT.equalsIgnoreCase(getString(unit))) {
639             // convert Fahrenheit to Celsius
640             return ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(temp).doubleValue();
641         }
642         return temp;
643     }
644 }