]> git.basschouten.com Git - openhab-addons.git/blob
ddec6f9624ff89c09ce5c4c051f3e88d674717b2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.shelly.internal.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 th Thing Handler instance
58      * @param profile ShellyDeviceProfile
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_NONE, 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 th Thing Handler instance
209      * @param profile ShellyDeviceProfile
210      * @param status Last ShellySettingsStatus
211      */
212     public static boolean updateMeters(ShellyThingInterface thingHandler, ShellySettingsStatus status) {
213         ShellyDeviceProfile profile = thingHandler.getProfile();
214
215         double accumulatedWatts = 0.0;
216         double accumulatedTotal = 0.0;
217         double accumulatedReturned = 0.0;
218
219         boolean updated = false;
220         // Devices without power meters get no updates
221         // We need to differ
222         // Roler+RGBW2 have multiple meters -> aggregate consumption to the functional device
223         // Meter and EMeter have a different set of channels
224         if (status.meters != null || status.emeters != null) {
225             if (!profile.isRoller && !profile.isRGBW2) {
226                 // In Relay mode we map eacher meter to the matching channel group
227                 int m = 0;
228                 if (!profile.isEMeter) {
229                     for (ShellySettingsMeter meter : status.meters) {
230                         if (m >= profile.numMeters) {
231                             // Shelly1: reports status.meters[0].is_valid = true, but even doesn't have a meter
232                             meter.isValid = false;
233                         }
234                         if (getBool(meter.isValid) || profile.isLight) { // RGBW2-white doesn't report valid flag
235                             // correctly in white mode
236                             String groupName = profile.getMeterGroup(m);
237                             if (!thingHandler.areChannelsCreated()) {
238                                 // skip for Shelly Bulb: JSON has a meter, but values don't get updated
239                                 if (!profile.isBulb) {
240                                     thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
241                                             .createMeterChannels(thingHandler.getThing(), meter, groupName));
242                                 }
243                             }
244
245                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
246                                     toQuantityType(getDouble(meter.power), DIGITS_WATT, Units.WATT));
247                             accumulatedWatts += getDouble(meter.power);
248
249                             // convert Watt/Min to kw/h
250                             if (meter.total != null) {
251                                 double kwh = getDouble(meter.total) / 1000 / 60;
252                                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
253                                         toQuantityType(kwh, DIGITS_KWH, Units.KILOWATT_HOUR));
254                                 accumulatedTotal += kwh;
255                             }
256                             if (meter.counters != null) {
257                                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
258                                         toQuantityType(getDouble(meter.counters[0]), DIGITS_WATT, Units.WATT));
259                             }
260                             if (meter.timestamp != null) {
261                                 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
262                                         getTimestamp(getString(profile.settings.timezone), meter.timestamp));
263                             }
264                         }
265                         m++;
266                     }
267                 } else {
268                     for (ShellySettingsEMeter emeter : status.emeters) {
269                         if (getBool(emeter.isValid)) {
270                             String groupName = profile.getMeterGroup(m);
271                             if (!thingHandler.areChannelsCreated()) {
272                                 thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
273                                         .createEMeterChannels(thingHandler.getThing(), profile, emeter, groupName));
274                             }
275
276                             // convert Watt/h to KW/h
277                             double total = getDouble(emeter.total) / 1000;
278                             double totalReturned = getDouble(emeter.totalReturned) / 1000;
279                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
280                                     toQuantityType(getDouble(emeter.power), DIGITS_WATT, Units.WATT));
281                             updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
282                                     toQuantityType(total, DIGITS_KWH, Units.KILOWATT_HOUR));
283                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_TOTALRET,
284                                     toQuantityType(totalReturned, DIGITS_KWH, Units.KILOWATT_HOUR));
285                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_REACTWATTS,
286                                     toQuantityType(getDouble(emeter.reactive), DIGITS_WATT, Units.WATT));
287                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_VOLTAGE,
288                                     toQuantityType(getDouble(emeter.voltage), DIGITS_VOLT, Units.VOLT));
289                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_CURRENT,
290                                     toQuantityType(getDouble(emeter.current), DIGITS_AMPERE, Units.AMPERE));
291                             updated |= thingHandler.updateChannel(groupName, CHANNEL_EMETER_PFACTOR,
292                                     toQuantityType(computePF(emeter), Units.PERCENT));
293
294                             accumulatedWatts += getDouble(emeter.power);
295                             accumulatedTotal += total;
296                             accumulatedReturned += totalReturned;
297                             if (updated) {
298                                 thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE, getTimestamp());
299                             }
300                         }
301                         m++;
302                     }
303                 }
304             } else {
305                 // In Roller Mode we accumulate all meters to a single set of meters
306                 double currentWatts = 0.0;
307                 double totalWatts = 0.0;
308                 double lastMin1 = 0.0;
309                 long timestamp = 0l;
310                 String groupName = CHANNEL_GROUP_METER;
311
312                 if (!thingHandler.areChannelsCreated()) {
313                     ShellySettingsMeter m = status.meters.get(0);
314                     if (getBool(m.isValid)) {
315                         // Create channels for 1 Meter
316                         thingHandler.updateChannelDefinitions(
317                                 ShellyChannelDefinitions.createMeterChannels(thingHandler.getThing(), m, groupName));
318                     }
319                 }
320
321                 for (ShellySettingsMeter meter : status.meters) {
322                     if (getBool(meter.isValid)) {
323                         currentWatts += getDouble(meter.power);
324                         totalWatts += getDouble(meter.total);
325                         if (meter.counters != null) {
326                             lastMin1 += getDouble(meter.counters[0]);
327                         }
328                         if (getLong(meter.timestamp) > timestamp) {
329                             timestamp = getLong(meter.timestamp); // newest one
330                         }
331                     }
332                 }
333
334                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_LASTMIN1,
335                         toQuantityType(getDouble(lastMin1), DIGITS_WATT, Units.WATT));
336
337                 // convert totalWatts into kw/h
338                 totalWatts = totalWatts / (60.0 * 1000.0);
339                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_CURRENTWATTS,
340                         toQuantityType(currentWatts, DIGITS_WATT, Units.WATT));
341                 updated |= thingHandler.updateChannel(groupName, CHANNEL_METER_TOTALKWH,
342                         toQuantityType(totalWatts, DIGITS_KWH, Units.KILOWATT_HOUR));
343
344                 if (updated && timestamp > 0) {
345                     thingHandler.updateChannel(groupName, CHANNEL_LAST_UPDATE,
346                             getTimestamp(getString(profile.settings.timezone), timestamp));
347                 }
348             }
349
350             if (!profile.isRoller && !profile.isRGBW2) {
351                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUWATTS, toQuantityType(
352                         status.totalPower != null ? status.totalPower : accumulatedWatts, DIGITS_WATT, Units.WATT));
353                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCUTOTAL,
354                         toQuantityType(status.totalCurrent != null ? status.totalCurrent / 1000 : accumulatedTotal,
355                                 DIGITS_KWH, Units.KILOWATT_HOUR));
356                 thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ACCURETURNED,
357                         toQuantityType(status.totalReturned != null ? status.totalReturned / 1000 : accumulatedReturned,
358                                 DIGITS_KWH, Units.KILOWATT_HOUR));
359             }
360         }
361
362         return updated;
363     }
364
365     private static Double computePF(ShellySettingsEMeter emeter) {
366         if (emeter.pf != null) { // EM3
367             return emeter.pf; // take device value
368         }
369
370         // EM: compute from provided values
371         if (emeter.reactive != null && Math.abs(emeter.power) + Math.abs(emeter.reactive) > 1.5) {
372             double pf = emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive);
373             return pf;
374         }
375         return 0.0;
376     }
377
378     /**
379      * Update Sensor channel
380      *
381      * @param th Thing Handler instance
382      * @param profile ShellyDeviceProfile
383      * @param status Last ShellySettingsStatus
384      *
385      * @throws ShellyApiException
386      */
387     public static boolean updateSensors(ShellyThingInterface thingHandler, ShellySettingsStatus status)
388             throws ShellyApiException {
389         ShellyDeviceProfile profile = thingHandler.getProfile();
390
391         boolean updated = false;
392         if (profile.isSensor || profile.hasBattery) {
393             ShellyStatusSensor sdata = thingHandler.getApi().getSensorStatus();
394             if (!thingHandler.areChannelsCreated()) {
395                 thingHandler.updateChannelDefinitions(
396                         ShellyChannelDefinitions.createSensorChannels(thingHandler.getThing(), profile, sdata));
397             }
398
399             updated |= thingHandler.updateWakeupReason(sdata.actReasons);
400
401             if ((sdata.sensor != null) && sdata.sensor.isValid) {
402                 // Shelly DW: “sensor”:{“state”:“open”, “is_valid”:true},
403                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
404                         getOpenClosed(getString(sdata.sensor.state).equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN)));
405                 String sensorError = sdata.sensorError;
406                 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR,
407                         getStringType(sensorError));
408                 if (changed && !"0".equals(sensorError)) {
409                     thingHandler.postEvent(getString(sdata.sensorError), true);
410                 }
411                 updated |= changed;
412             }
413             if (sdata.tmp != null && getBool(sdata.tmp.isValid)) {
414                 Double temp = getString(sdata.tmp.units).toUpperCase().equals(SHELLY_TEMP_CELSIUS)
415                         ? getDouble(sdata.tmp.tC)
416                         : getDouble(sdata.tmp.tF);
417                 updated |= updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
418                         temp.doubleValue(), getString(sdata.tmp.units));
419             } else if (status.thermostats != null) {
420                 // Shelly TRV
421                 if (profile.settings.thermostats != null) {
422                     ShellyThermnostat ps = profile.settings.thermostats.get(0);
423                     ShellyThermnostat t = status.thermostats.get(0);
424                     int bminutes = getInteger(t.boostMinutes) >= 0 ? getInteger(t.boostMinutes)
425                             : getInteger(ps.boostMinutes);
426                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BCONTROL,
427                             getOnOff(getInteger(t.boostMinutes) > 0));
428                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_BTIMER,
429                             toQuantityType((double) bminutes, DIGITS_NONE, Units.MINUTE));
430                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_MODE, getStringType(
431                             getBool(t.targetTemp.enabled) ? SHELLY_TRV_MODE_AUTO : SHELLY_TRV_MODE_MANUAL));
432
433                     int pid = getBool(t.schedule) ? getInteger(t.profile) : 0;
434                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_SCHEDULE,
435                             getOnOff(t.schedule));
436                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE,
437                             getStringType(profile.getValueProfile(0, pid)));
438                     if (t.tmp != null) {
439                         updated |= updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
440                                 t.tmp.value, t.tmp.units);
441                         updated |= updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, CHANNEL_CONTROL_SETTEMP,
442                                 t.targetTemp.value, t.targetTemp.unit);
443                     }
444                     if (t.pos != null) {
445                         updated |= thingHandler.updateChannel(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_POSITION,
446                                 t.pos != -1 ? toQuantityType(t.pos, DIGITS_NONE, Units.PERCENT) : UnDefType.UNDEF);
447                         updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
448                                 getOpenClosed(getDouble(t.pos) > 0));
449                     }
450                 }
451             }
452
453             if (sdata.hum != null) {
454                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_HUM,
455                         toQuantityType(getDouble(sdata.hum.value), DIGITS_PERCENT, Units.PERCENT));
456             }
457             if ((sdata.lux != null) && getBool(sdata.lux.isValid)) {
458                 // “lux”:{“value”:30, “illumination”: “dark”, “is_valid”:true},
459                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_LUX,
460                         toQuantityType(getDouble(sdata.lux.value), DIGITS_LUX, Units.LUX));
461                 if (sdata.lux.illumination != null) {
462                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM,
463                             getStringType(sdata.lux.illumination));
464                 }
465             }
466             if (sdata.accel != null) {
467                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
468                         toQuantityType(getDouble(sdata.accel.tilt.doubleValue()), DIGITS_NONE, Units.DEGREE_ANGLE));
469             }
470             if (sdata.flood != null) {
471                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
472                         getOnOff(sdata.flood));
473             }
474             if (sdata.smoke != null) {
475                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SMOKE,
476                         getOnOff(sdata.smoke));
477             }
478             if (sdata.mute != null) {
479                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MUTE, getOnOff(sdata.mute));
480             }
481
482             if (sdata.gasSensor != null) {
483                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
484                         getStringType(sdata.gasSensor.selfTestState));
485                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
486                         getStringType(sdata.gasSensor.alarmState));
487                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE,
488                         getStringType(sdata.gasSensor.sensorState));
489             }
490             if ((sdata.concentration != null) && sdata.concentration.isValid) {
491                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, toQuantityType(
492                         getInteger(sdata.concentration.ppm).doubleValue(), DIGITS_NONE, Units.PARTS_PER_MILLION));
493             }
494             if ((sdata.adcs != null) && (sdata.adcs.size() > 0)) {
495                 ShellyADC adc = sdata.adcs.get(0);
496                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VOLTAGE,
497                         toQuantityType(getDouble(adc.voltage), 2, Units.VOLT));
498             }
499
500             boolean charger = (getInteger(profile.settings.externalPower) == 1) || getBool(sdata.charger);
501             if ((profile.settings.externalPower != null) || (sdata.charger != null)) {
502                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
503                         getOnOff(charger));
504             }
505             if (sdata.bat != null) { // no update for Sense
506                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
507                         toQuantityType(getDouble(sdata.bat.value), 0, Units.PERCENT));
508
509                 int lowBattery = thingHandler.getThingConfig().lowBattery;
510                 boolean changed = thingHandler.updateChannel(CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LOW,
511                         getOnOff(!charger && getDouble(sdata.bat.value) < lowBattery));
512                 updated |= changed;
513                 if (!charger && changed && getDouble(sdata.bat.value) < lowBattery) {
514                     thingHandler.postEvent(ALARM_TYPE_LOW_BATTERY, false);
515                 }
516             }
517
518             if (sdata.motion != null) { // Shelly Sense
519                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
520                         getOnOff(sdata.motion));
521             }
522             if (sdata.sensor != null) { // Shelly Motion
523                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_ACT,
524                         getOnOff(sdata.sensor.motionActive));
525                 updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
526                         getOnOff(sdata.sensor.motion));
527                 long timestamp = getLong(sdata.sensor.motionTimestamp);
528                 if (timestamp != 0) {
529                     updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION_TS,
530                             getTimestamp(getString(profile.settings.timezone), timestamp));
531                 }
532             }
533
534             updated |= thingHandler.updateInputs(status);
535
536             if (updated) {
537                 thingHandler.updateChannel(profile.getControlGroup(0), CHANNEL_LAST_UPDATE, getTimestamp());
538             }
539         }
540         return updated;
541     }
542
543     public static boolean updateDimmers(ShellyThingInterface thingHandler, ShellySettingsStatus orgStatus)
544             throws ShellyApiException {
545         boolean updated = false;
546         ShellyDeviceProfile profile = thingHandler.getProfile();
547         if (profile.isDimmer) {
548             // We need to fixup the returned Json: The dimmer returns light[] element, which is ok, but it doesn't have
549             // the same structure as lights[] from Bulb,RGBW2 and Duo. The tag gets replaced by dimmers[] so that Gson
550             // maps to a different structure (ShellyShortLight).
551             Gson gson = new Gson();
552             ShellySettingsStatus dstatus = !profile.isGen2
553                     ? fromJson(gson, Shelly1ApiJsonDTO.fixDimmerJson(orgStatus.json), ShellySettingsStatus.class)
554                     : orgStatus;
555
556             int l = 0;
557             for (ShellyShortLightStatus dimmer : dstatus.dimmers) {
558                 Integer r = l + 1;
559                 String groupName = profile.numRelays <= 1 ? CHANNEL_GROUP_DIMMER_CONTROL
560                         : CHANNEL_GROUP_DIMMER_CONTROL + r.toString();
561
562                 if (!thingHandler.areChannelsCreated()) {
563                     thingHandler.updateChannelDefinitions(ShellyChannelDefinitions
564                             .createDimmerChannels(thingHandler.getThing(), profile, dstatus, l));
565                 }
566
567                 ShellySettingsDimmer ds = profile.settings.dimmers.get(l);
568                 if (ds.name != null) {
569                     updated |= thingHandler.updateChannel(groupName, CHANNEL_OUTPUT_NAME, getStringType(ds.name));
570                 }
571
572                 // On a status update we map a dimmer.ison = false to brightness 0 rather than the device's brightness
573                 // and send an OFF status to the same channel.
574                 // When the device's brightness is > 0 we send the new value to the channel and an ON command
575                 if (dimmer.ison) {
576                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Switch", OnOffType.ON);
577                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Value",
578                             toQuantityType((double) getInteger(dimmer.brightness), DIGITS_NONE, Units.PERCENT));
579                 } else {
580                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Switch", OnOffType.OFF);
581                     updated |= thingHandler.updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Value",
582                             toQuantityType(0.0, DIGITS_NONE, Units.PERCENT));
583                 }
584
585                 if (profile.settings.dimmers != null) {
586                     ShellySettingsDimmer dsettings = profile.settings.dimmers.get(l);
587                     if (dsettings != null) {
588                         updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_AUTOON,
589                                 toQuantityType(getDouble(dsettings.autoOn), Units.SECOND));
590                         updated |= thingHandler.updateChannel(groupName, CHANNEL_TIMER_AUTOOFF,
591                                 toQuantityType(getDouble(dsettings.autoOff), Units.SECOND));
592                     }
593                 }
594
595                 l++;
596             }
597         }
598         return updated;
599     }
600
601     public static boolean updateTempChannel(@Nullable ShellyShortTemp sensor, ShellyThingInterface thingHandler,
602             String channel) {
603         return sensor != null ? updateTempChannel(thingHandler, CHANNEL_GROUP_SENSOR, channel, sensor.tC, "") : false;
604     }
605
606     public static boolean updateTempChannel(ShellyThingInterface thingHandler, String group, String channel,
607             @Nullable Double temp, @Nullable String unit) {
608         if (temp == null || temp == SHELLY_API_INVTEMP) {
609             return false;
610         }
611         return thingHandler.updateChannel(group, channel,
612                 toQuantityType(convertToC(temp, unit), DIGITS_TEMP, SIUnits.CELSIUS));
613     }
614
615     private static Double convertToC(@Nullable Double temp, @Nullable String unit) {
616         if (temp == null || temp == SHELLY_API_INVTEMP) {
617             return SHELLY_API_INVTEMP;
618         }
619         if (SHELLY_TEMP_FAHRENHEIT.equalsIgnoreCase(getString(unit))) {
620             // convert Fahrenheit to Celsius
621             return ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(temp).doubleValue();
622         }
623         return temp;
624     }
625 }