]> git.basschouten.com Git - openhab-addons.git/blob
7ff8a699218e75f0046d8bca530cc583041c1843
[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.api2;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.CHANNEL_INPUT;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.*;
18 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19
20 import java.util.ArrayList;
21 import java.util.Map;
22 import java.util.Random;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.openhab.binding.shelly.internal.api.ShellyApiException;
28 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
29 import org.openhab.binding.shelly.internal.api.ShellyHttpClient;
30 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyFavPos;
31 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
32 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyRollerStatus;
33 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySensorTmp;
34 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDimmer;
35 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsEMeter;
36 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsInput;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsMeter;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRoller;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortStatusRelay;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusRelay;
44 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor;
45 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtAnalogInput;
46 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtDigitalInput;
47 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtHumidity;
48 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtTemperature;
49 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtTemperature.ShellyShortTemp;
50 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtVoltage;
51 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellySensorBat;
52 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellySensorHum;
53 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellySensorLux;
54 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2AuthRsp;
55 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DevConfigCover;
56 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DevConfigInput;
57 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DevConfigSwitch;
58 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2GetConfigResult;
59 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusLight;
60 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult;
61 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2CoverStatus;
62 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusEm;
63 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusHumidity;
64 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusIlluminance;
65 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusPower;
66 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusSmoke;
67 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusTempId;
68 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2InputStatus;
69 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RelayStatus;
70 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcBaseMessage;
71 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2StatusEm1;
72 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
73 import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
74 import org.openhab.binding.shelly.internal.handler.ShellyComponents;
75 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
76 import org.openhab.core.types.State;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79
80 /**
81  * {@link Shelly2ApiClient} Low level part of the RPC API
82  *
83  * @author Markus Michels - Initial contribution
84  */
85 @NonNullByDefault
86 public class Shelly2ApiClient extends ShellyHttpClient {
87     private final Logger logger = LoggerFactory.getLogger(Shelly2ApiClient.class);
88     protected final Random random = new Random();
89     protected final ShellyStatusRelay relayStatus = new ShellyStatusRelay();
90     protected final ShellyStatusSensor sensorData = new ShellyStatusSensor();
91     protected final ArrayList<ShellyRollerStatus> rollerStatus = new ArrayList<>();
92     protected @Nullable ShellyThingInterface thing;
93     protected @Nullable Shelly2AuthRsp authReq;
94
95     public Shelly2ApiClient(String thingName, ShellyThingInterface thing) {
96         super(thingName, thing);
97         this.thing = thing;
98     }
99
100     public Shelly2ApiClient(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
101         super(thingName, config, httpClient);
102     }
103
104     protected static final Map<String, String> MAP_INMODE_BTNTYPE = Map.of(//
105             SHELLY2_BTNT_MOMENTARY, SHELLY_BTNT_MOMENTARY, //
106             SHELLY2_BTNT_FLIP, SHELLY_BTNT_TOGGLE, //
107             SHELLY2_BTNT_FOLLOW, SHELLY_BTNT_EDGE, //
108             SHELLY2_BTNT_DETACHED, SHELLY_BTNT_MOMENTARY);
109
110     protected static final Map<String, String> MAP_INPUT_EVENT_TYPE = Map.of(//
111             SHELLY2_EVENT_1PUSH, SHELLY_BTNEVENT_1SHORTPUSH, //
112             SHELLY2_EVENT_2PUSH, SHELLY_BTNEVENT_2SHORTPUSH, //
113             SHELLY2_EVENT_3PUSH, SHELLY_BTNEVENT_3SHORTPUSH, //
114             SHELLY2_EVENT_LPUSH, SHELLY_BTNEVENT_LONGPUSH, //
115             SHELLY2_EVENT_LSPUSH, SHELLY_BTNEVENT_LONGSHORTPUSH, //
116             SHELLY2_EVENT_SLPUSH, SHELLY_BTNEVENT_SHORTLONGPUSH);
117
118     protected static final Map<String, String> MAP_INPUT_EVENT_ID = Map.of(//
119             SHELLY2_EVENT_BTNUP, SHELLY_EVENT_BTN_OFF, //
120             SHELLY2_EVENT_BTNDOWN, SHELLY_EVENT_BTN_ON, //
121             SHELLY2_EVENT_1PUSH, SHELLY_EVENT_SHORTPUSH, //
122             SHELLY2_EVENT_2PUSH, SHELLY_EVENT_DOUBLE_SHORTPUSH, //
123             SHELLY2_EVENT_3PUSH, SHELLY_EVENT_TRIPLE_SHORTPUSH, //
124             SHELLY2_EVENT_LPUSH, SHELLY_EVENT_LONGPUSH, //
125             SHELLY2_EVENT_LSPUSH, SHELLY_EVENT_LONG_SHORTPUSH, //
126             SHELLY2_EVENT_SLPUSH, SHELLY_EVENT_SHORT_LONGTPUSH);
127
128     protected static final Map<String, String> MAP_INPUT_MODE = Map.of(//
129             SHELLY2_RMODE_SINGLE, SHELLY_INP_MODE_ONEBUTTON, //
130             SHELLY2_RMODE_DUAL, SHELLY_INP_MODE_OPENCLOSE, //
131             SHELLY2_RMODE_DETACHED, SHELLY_INP_MODE_ONEBUTTON);
132
133     protected static final Map<String, String> MAP_ROLLER_STATE = Map.of(//
134             SHELLY2_RSTATE_OPEN, SHELLY_RSTATE_OPEN, //
135             SHELLY2_RSTATE_CLOSED, SHELLY_RSTATE_CLOSE, //
136             SHELLY2_RSTATE_OPENING, SHELLY2_RSTATE_OPENING, // Gen2-only
137             SHELLY2_RSTATE_CLOSING, SHELLY2_RSTATE_CLOSING, // Gen2-only
138             SHELLY2_RSTATE_STOPPED, SHELLY_RSTATE_STOP, //
139             SHELLY2_RSTATE_CALIB, SHELLY2_RSTATE_CALIB); // Gen2-only
140
141     protected static final Map<String, String> MAP_PROFILE = Map.of(//
142             SHELLY_CLASS_RELAY, SHELLY2_PROFILE_RELAY, //
143             SHELLY_CLASS_ROLLER, SHELLY2_PROFILE_COVER);
144
145     protected @Nullable ArrayList<@Nullable ShellySettingsRelay> fillRelaySettings(ShellyDeviceProfile profile,
146             Shelly2GetConfigResult dc) {
147         ArrayList<@Nullable ShellySettingsRelay> relays = new ArrayList<>();
148         addRelaySettings(relays, dc.switch0);
149         addRelaySettings(relays, dc.switch1);
150         addRelaySettings(relays, dc.switch2);
151         addRelaySettings(relays, dc.switch3);
152         addRelaySettings(relays, dc.switch100);
153         return !relays.isEmpty() ? relays : null;
154     }
155
156     private void addRelaySettings(ArrayList<@Nullable ShellySettingsRelay> relays,
157             @Nullable Shelly2DevConfigSwitch cs) {
158         if (cs == null) {
159             return;
160         }
161
162         ShellySettingsRelay rsettings = new ShellySettingsRelay();
163         rsettings.id = cs.id;
164         rsettings.isValid = cs.id != null;
165         rsettings.name = cs.name;
166         rsettings.ison = false;
167         rsettings.autoOn = getBool(cs.autoOn) ? cs.autoOnDelay : 0;
168         rsettings.autoOff = getBool(cs.autoOff) ? cs.autoOffDelay : 0;
169         rsettings.hasTimer = false;
170         rsettings.btnType = mapValue(MAP_INMODE_BTNTYPE, getString(cs.mode).toLowerCase());
171         relays.add(rsettings);
172     }
173
174     protected boolean fillDeviceStatus(ShellySettingsStatus status, Shelly2DeviceStatusResult result,
175             boolean channelUpdate) throws ShellyApiException {
176         boolean updated = false;
177
178         if (result.temperature0 != null && result.temperature0.tC != null && !getProfile().isSensor) {
179             if (status.tmp == null) {
180                 status.tmp = new ShellySensorTmp();
181             }
182             status.temperature = status.tmp.tC = result.temperature0.tC;
183         }
184
185         updated |= updateInputStatus(status, result, channelUpdate);
186         updated |= updateRelayStatus(status, result.switch0, channelUpdate);
187         updated |= updateRelayStatus(status, result.switch1, channelUpdate);
188         updated |= updateRelayStatus(status, result.switch2, channelUpdate);
189         updated |= updateRelayStatus(status, result.switch3, channelUpdate);
190         updated |= updateRelayStatus(status, result.switch100, channelUpdate);
191         updated |= updateRelayStatus(status, result.pm10, channelUpdate);
192         updated |= updateEmStatus(status, result.em0, channelUpdate);
193         updated |= updateEmStatus(status, result.em10, channelUpdate);
194         updated |= updateEmStatus(status, result.em11, channelUpdate);
195         updated |= updateRollerStatus(status, result.cover0, channelUpdate);
196         updated |= updateDimmerStatus(status, result.light0, channelUpdate);
197         if (channelUpdate) {
198             updated |= ShellyComponents.updateMeters(getThing(), status);
199         }
200
201         updateHumidityStatus(sensorData, result.humidity0);
202         updateTemperatureStatus(sensorData, result.temperature0);
203         updateIlluminanceStatus(sensorData, result.illuminance0);
204         updateSmokeStatus(sensorData, result.smoke0);
205         updateBatteryStatus(sensorData, result.devicepower0);
206         updateAddonStatus(status, result);
207         updated |= ShellyComponents.updateSensors(getThing(), status);
208         return updated;
209     }
210
211     private boolean updateRelayStatus(ShellySettingsStatus status, @Nullable Shelly2RelayStatus rs,
212             boolean channelUpdate) throws ShellyApiException {
213         if (rs == null) {
214             return false;
215         }
216         ShellyDeviceProfile profile = getProfile();
217
218         ShellySettingsRelay rstatus;
219         ShellyShortStatusRelay sr;
220         int rIdx = getRelayIdx(profile, rs.id);
221         if (profile.hasRelays) {
222             if (rIdx == -1) {
223                 throw new IllegalArgumentException("Update for invalid relay index");
224             }
225             rstatus = status.relays.get(rIdx);
226             sr = relayStatus.relays.get(rIdx);
227         } else {
228             rstatus = new ShellySettingsRelay();
229             sr = new ShellyShortStatusRelay();
230             rIdx = rs.id;
231         }
232
233         sr.isValid = rstatus.isValid = true;
234         sr.name = rstatus.name = status.name;
235         if (rs.output != null) {
236             sr.ison = rstatus.ison = getBool(rs.output);
237         }
238         if (getDouble(rs.timerStartetAt) > 0) {
239             int duration = (int) (now() - rs.timerStartetAt);
240             sr.timerRemaining = duration;
241         }
242         if (status.tmp == null) {
243             status.tmp = new ShellySensorTmp();
244         }
245         if (rs.temperature != null) {
246             if (status.tmp == null) {
247                 status.tmp = new ShellySensorTmp();
248             }
249             status.tmp.isValid = true;
250             status.tmp.tC = rs.temperature.tC;
251             status.tmp.tF = rs.temperature.tF;
252             status.tmp.units = "C";
253             sr.temperature = getDouble(rs.temperature.tC);
254             if (status.temperature == null || getDouble(rs.temperature.tC) > status.temperature) {
255                 status.temperature = sr.temperature;
256             }
257         }
258
259         if (rs.errors != null) {
260             for (String error : rs.errors) {
261                 sr.overpower = rstatus.overpower = SHELLY2_ERROR_OVERPOWER.equals(error);
262                 status.overload = SHELLY2_ERROR_OVERVOLTAGE.equals(error);
263                 status.overtemperature = SHELLY2_ERROR_OVERTEMP.equals(error);
264             }
265             sr.overtemperature = status.overtemperature;
266         }
267
268         ShellySettingsMeter sm = new ShellySettingsMeter();
269         ShellySettingsEMeter emeter = status.emeters != null ? status.emeters.get(rIdx) : new ShellySettingsEMeter();
270         if (rs.apower != null) {
271             sm.power = emeter.power = rs.apower;
272         }
273         if (rs.aenergy != null) {
274             // Gen2 reports Watt, needs to be converted to W/h
275             sm.total = emeter.total = rs.aenergy.total;
276             sm.counters = rs.aenergy.byMinute;
277             sm.timestamp = rs.aenergy.minuteTs;
278         }
279         if (rs.voltage != null) {
280             emeter.voltage = rs.voltage;
281         }
282         if (rs.current != null) {
283             emeter.current = rs.current;
284         }
285         if (rs.pf != null) {
286             emeter.pf = rs.pf;
287         }
288
289         if (profile.hasRelays) {
290             // Update internal structures
291             status.relays.set(rIdx, rstatus);
292             relayStatus.relays.set(rIdx, sr);
293         }
294
295         updateMeter(status, rIdx, sm, emeter, channelUpdate);
296         return channelUpdate && profile.hasRelays
297                 ? ShellyComponents.updateRelay((ShellyBaseHandler) getThing(), status, rIdx)
298                 : false;
299     }
300
301     private int getRelayIdx(ShellyDeviceProfile profile, @Nullable Integer id) {
302         if (id != null && profile.settings.relays != null) {
303             int idx = 0;
304             for (ShellySettingsRelay relay : profile.settings.relays) {
305                 if (relay.isValid && relay.id != null && relay.id.intValue() == id.intValue()) {
306                     return idx;
307                 }
308                 idx++;
309             }
310         }
311         return -1;
312     }
313
314     private void updateMeter(ShellySettingsStatus status, int id, ShellySettingsMeter sm, ShellySettingsEMeter emeter,
315             boolean channelUpdate) throws ShellyApiException {
316         if (getProfile().numMeters == 0) {
317             return;
318         }
319         sm.isValid = sm.power != null || sm.total != null;
320         emeter.isValid = emeter.current != null || emeter.voltage != null || emeter.power != null
321                 || emeter.total != null;
322         status.meters.set(id, sm);
323         status.emeters.set(id, emeter);
324         relayStatus.meters.set(id, sm);
325     }
326
327     private boolean updateEmStatus(ShellySettingsStatus status, @Nullable Shelly2StatusEm1 em, boolean channelUpdate)
328             throws ShellyApiException {
329         if (em == null) {
330             return false;
331         }
332
333         ShellySettingsMeter sm = new ShellySettingsMeter();
334         ShellySettingsEMeter emeter = status.emeters.get(em.id);
335         if (em.actPower != null) {
336             sm.power = emeter.power = em.actPower;
337         }
338         if (em.aptrPower != null) {
339             emeter.totalReturned = em.aptrPower;
340         }
341         if (em.voltage != null) {
342             emeter.voltage = em.voltage;
343         }
344         if (em.current != null) {
345             emeter.current = em.current;
346         }
347         if (em.pf != null) {
348             emeter.pf = em.pf;
349         }
350         // Update internal structures
351         updateMeter(status, em.id, sm, emeter, channelUpdate);
352
353         postAlarms(em.errors);
354         return channelUpdate ? ShellyComponents.updateMeters(getThing(), status) : false;
355     }
356
357     private boolean updateEmStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusEm em,
358             boolean channelUpdate) throws ShellyApiException {
359         if (em == null) {
360             return false;
361         }
362
363         if (em.totalCurrent != null) {
364             status.totalCurrent = em.totalCurrent;
365         }
366         if (em.totalActPower != null) {
367             status.totalPower = em.totalActPower;
368         }
369         if (em.totalAprtPower != null) {
370             status.totalReturned = em.totalAprtPower;
371         }
372
373         ShellySettingsMeter sm = new ShellySettingsMeter();
374         ShellySettingsEMeter emeter = status.emeters.get(0);
375         if (em.aActPower != null) {
376             sm.power = emeter.power = em.aActPower;
377         }
378         if (em.aAprtPower != null) {
379             emeter.totalReturned = em.aAprtPower;
380         }
381         if (em.aVoltage != null) {
382             emeter.voltage = em.aVoltage;
383         }
384         if (em.aCurrent != null) {
385             emeter.current = em.aCurrent;
386         }
387         if (em.aPF != null) {
388             emeter.pf = em.aPF;
389         }
390         // Update internal structures
391         updateMeter(status, 0, sm, emeter, channelUpdate);
392
393         if (status.emeters.size() > 1) {
394             sm = new ShellySettingsMeter();
395             emeter = status.emeters.get(1);
396             sm.isValid = emeter.isValid = true;
397             if (em.bActPower != null) {
398                 sm.power = emeter.power = em.bActPower;
399             }
400             if (em.bAprtPower != null) {
401                 emeter.totalReturned = em.bAprtPower;
402             }
403             if (em.bVoltage != null) {
404                 emeter.voltage = em.bVoltage;
405             }
406             if (em.bCurrent != null) {
407                 emeter.current = em.bCurrent;
408             }
409             if (em.bPF != null) {
410                 emeter.pf = em.bPF;
411             }
412             // Update internal structures
413             updateMeter(status, 1, sm, emeter, channelUpdate);
414         }
415
416         if (status.emeters.size() > 2) {
417             sm = new ShellySettingsMeter();
418             emeter = status.emeters.get(2);
419             sm.isValid = emeter.isValid = true;
420             if (em.cActPower != null) {
421                 sm.power = emeter.power = em.cActPower;
422             }
423             if (em.cAprtPower != null) {
424                 emeter.totalReturned = em.cAprtPower;
425             }
426             if (em.cVoltage != null) {
427                 emeter.voltage = em.cVoltage;
428             }
429             if (em.cCurrent != null) {
430                 emeter.current = em.cCurrent;
431             }
432             if (em.cPF != null) {
433                 emeter.pf = em.cPF;
434             }
435             // Update internal structures
436             updateMeter(status, 2, sm, emeter, channelUpdate);
437         }
438
439         return channelUpdate ? ShellyComponents.updateMeters(getThing(), status) : false;
440     }
441
442     protected @Nullable ArrayList<@Nullable ShellySettingsRoller> fillRollerSettings(ShellyDeviceProfile profile,
443             Shelly2GetConfigResult dc) {
444         if (dc.cover0 == null) {
445             return null;
446         }
447
448         ArrayList<@Nullable ShellySettingsRoller> rollers = new ArrayList<>();
449
450         addRollerSettings(rollers, dc.cover0);
451         fillRollerFavorites(profile, dc);
452         return rollers;
453     }
454
455     private void addRollerSettings(ArrayList<@Nullable ShellySettingsRoller> rollers,
456             @Nullable Shelly2DevConfigCover coverConfig) {
457         if (coverConfig == null) {
458             return;
459         }
460
461         ShellySettingsRoller settings = new ShellySettingsRoller();
462         settings.isValid = true;
463         settings.defaultState = coverConfig.initialState;
464         settings.inputMode = mapValue(MAP_INPUT_MODE, coverConfig.inMode);
465         settings.btnReverse = getBool(coverConfig.invertDirections) ? 1 : 0;
466         settings.swapInputs = coverConfig.swapInputs;
467         settings.maxtime = 0.0; // n/a
468         settings.maxtimeOpen = coverConfig.maxtimeOpen;
469         settings.maxtimeClose = coverConfig.maxtimeClose;
470         if (coverConfig.safetySwitch != null) {
471             settings.safetySwitch = coverConfig.safetySwitch.enable;
472             settings.safetyAction = coverConfig.safetySwitch.action;
473         }
474         if (coverConfig.obstructionDetection != null) {
475             settings.obstacleAction = coverConfig.obstructionDetection.action;
476             settings.obstacleDelay = coverConfig.obstructionDetection.holdoff.intValue();
477             settings.obstaclePower = coverConfig.obstructionDetection.powerThr;
478         }
479         rollers.add(settings);
480     }
481
482     private void fillRollerFavorites(ShellyDeviceProfile profile, Shelly2GetConfigResult dc) {
483         if (dc.sys.uiData.cover != null) {
484             String[] favorites = dc.sys.uiData.cover.split(",");
485             profile.settings.favorites = new ArrayList<>();
486             for (int i = 0; i < favorites.length; i++) {
487                 ShellyFavPos fav = new ShellyFavPos();
488                 fav.pos = Integer.parseInt(favorites[i]);
489                 fav.name = fav.pos + "%";
490                 profile.settings.favorites.add(fav);
491             }
492             profile.settings.favoritesEnabled = !profile.settings.favorites.isEmpty();
493             logger.debug("{}: Roller Favorites loaded: {}", thingName,
494                     profile.settings.favoritesEnabled ? profile.settings.favorites.size() : "none");
495         }
496     }
497
498     private boolean updateRollerStatus(ShellySettingsStatus status, @Nullable Shelly2CoverStatus cs,
499             boolean updateChannels) throws ShellyApiException {
500         if (cs == null) {
501             return false;
502         }
503
504         ShellyRollerStatus rs = status.rollers.get(cs.id);
505         ShellySettingsMeter sm = status.meters.get(cs.id);
506         ShellySettingsEMeter emeter = status.emeters.get(cs.id);
507         rs.isValid = sm.isValid = emeter.isValid = true;
508         if (cs.state != null) {
509             if (!getString(rs.state).equals(cs.state)) {
510                 logger.debug("{}: Roller status changed from {} to {}, updateChannels={}", thingName, rs.state,
511                         mapValue(MAP_ROLLER_STATE, cs.state), updateChannels);
512             }
513             rs.state = mapValue(MAP_ROLLER_STATE, cs.state);
514             rs.calibrating = SHELLY2_RSTATE_CALIB.equals(cs.state);
515         }
516         if (cs.currentPos != null) {
517             rs.currentPos = cs.currentPos;
518         }
519         if (cs.moveStartedAt != null) {
520             rs.duration = (int) (now() - cs.moveStartedAt.longValue());
521         }
522         if (cs.temperature != null && cs.temperature.tC > getDouble(status.temperature)) {
523             if (status.tmp == null) {
524                 status.tmp = new ShellySensorTmp();
525             }
526             status.temperature = status.tmp.tC = getDouble(cs.temperature.tC);
527         }
528         if (cs.apower != null) {
529             rs.power = sm.power = emeter.power = cs.apower;
530         }
531         if (cs.aenergy != null) {
532             sm.total = emeter.total = cs.aenergy.total;
533             sm.counters = cs.aenergy.byMinute;
534             if (cs.aenergy.minuteTs != null) {
535                 sm.timestamp = (long) cs.aenergy.minuteTs;
536             }
537         }
538         if (cs.voltage != null) {
539             emeter.voltage = cs.voltage;
540         }
541         if (cs.current != null) {
542             emeter.current = cs.current;
543         }
544         if (cs.pf != null) {
545             emeter.pf = cs.pf;
546         }
547
548         rollerStatus.set(cs.id, rs);
549         status.rollers.set(cs.id, rs);
550         relayStatus.meters.set(cs.id, sm);
551         status.meters.set(cs.id, sm);
552         status.emeters.set(cs.id, emeter);
553
554         postAlarms(cs.errors);
555         if (rs.calibrating != null && rs.calibrating) {
556             getThing().postEvent(SHELLY_EVENT_ROLLER_CALIB, false);
557         }
558
559         return updateChannels ? ShellyComponents.updateRoller((ShellyBaseHandler) getThing(), rs, cs.id) : false;
560     }
561
562     protected void fillDimmerSettings(ShellyDeviceProfile profile, Shelly2GetConfigResult dc) {
563         if (!profile.isDimmer || dc.light0 == null) {
564             return;
565         }
566
567         if (profile.settings.dimmers != null) {
568             ShellySettingsDimmer ds = profile.settings.dimmers.get(0);
569             ds.autoOn = dc.light0.autoOnDelay;
570             ds.autoOff = dc.light0.autoOffDelay;
571             ds.name = dc.light0.name;
572             profile.settings.dimmers.set(0, ds);
573         }
574     }
575
576     private boolean updateDimmerStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusLight value,
577             boolean channelUpdate) throws ShellyApiException {
578         ShellyDeviceProfile profile = getProfile();
579         if (!profile.isDimmer || value == null) {
580             return false;
581         }
582
583         ShellyShortLightStatus ds = status.dimmers.get(0);
584         if (value.brightness != null) {
585             ds.brightness = value.brightness.intValue();
586         }
587         ds.ison = value.output;
588         ds.hasTimer = value.timerStartedAt != null;
589         ds.timerDuration = getDuration(value.timerStartedAt, value.timerDuration);
590         status.dimmers.set(0, ds);
591         return channelUpdate ? ShellyComponents.updateDimmers(getThing(), status) : false;
592     }
593
594     protected @Nullable Integer getDuration(@Nullable Double timerStartedAt, @Nullable Integer timerDuration) {
595         if (timerStartedAt == null || timerDuration == null) {
596             return null;
597         }
598         int duration = (int) (now() - timerStartedAt.longValue());
599         return duration <= timerDuration ? timerDuration - duration : 0;
600     }
601
602     // Addon
603     private void updateAddonStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusResult ds)
604             throws ShellyApiException {
605         if (ds == null) {
606             return;
607         }
608
609         if (ds.temperature100 != null) {
610             if (status.extTemperature == null) {
611                 status.extTemperature = new ShellyExtTemperature();
612             }
613             status.extTemperature.sensor1 = updateExtTempSensor(ds.temperature100);
614             status.extTemperature.sensor2 = updateExtTempSensor(ds.temperature101);
615             status.extTemperature.sensor3 = updateExtTempSensor(ds.temperature102);
616             status.extTemperature.sensor4 = updateExtTempSensor(ds.temperature103);
617             status.extTemperature.sensor5 = updateExtTempSensor(ds.temperature104);
618         }
619         if (ds.humidity100 != null) {
620             status.extHumidity = new ShellyExtHumidity(ds.humidity100.rh);
621         }
622         if (ds.voltmeter100 != null) {
623             status.extVoltage = new ShellyExtVoltage(ds.voltmeter100.voltage);
624         }
625         if (ds.input100 != null) {
626             status.extDigitalInput = new ShellyExtDigitalInput(getBool(ds.input100.state));
627         }
628     }
629
630     private @Nullable ShellyShortTemp updateExtTempSensor(@Nullable Shelly2DeviceStatusTempId value) {
631         if (value != null) {
632             ShellyShortTemp temp = new ShellyShortTemp();
633             temp.hwID = value.id.toString();
634             temp.tC = value.tC;
635             temp.tF = value.tF;
636             return temp;
637         }
638         return null;
639     }
640
641     protected void updateHumidityStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusHumidity value) {
642         if (value == null) {
643             return;
644         }
645         if (sdata.hum == null) {
646             sdata.hum = new ShellySensorHum();
647         }
648         sdata.hum.value = getDouble(value.rh);
649     }
650
651     protected void updateTemperatureStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusTempId value) {
652         if (value == null) {
653             return;
654         }
655         if (sdata.tmp == null) {
656             sdata.tmp = new ShellySensorTmp();
657         }
658         sdata.tmp.isValid = true;
659         sdata.tmp.units = SHELLY_TEMP_CELSIUS;
660         sdata.tmp.tC = value.tC;
661         sdata.tmp.tF = value.tF;
662     }
663
664     protected void updateIlluminanceStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusIlluminance value) {
665         if (value == null) {
666             return;
667         }
668         if (sdata.lux == null) {
669             sdata.lux = new ShellySensorLux();
670         }
671         sdata.lux.isValid = value.lux != null;
672         sdata.lux.value = value.lux;
673         sdata.lux.illumination = value.illumination;
674     }
675
676     protected void updateSmokeStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusSmoke value) {
677         if (value == null) {
678             return;
679         }
680         sdata.smoke = getBool(value.alarm);
681         sdata.mute = getBool(value.mute);
682     }
683
684     protected void updateBatteryStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusPower value) {
685         if (value == null) {
686             return;
687         }
688         if (sdata.bat == null) {
689             sdata.bat = new ShellySensorBat();
690         }
691
692         if (value.battery != null) {
693             sdata.bat.voltage = value.battery.volt;
694             sdata.bat.value = value.battery.percent;
695         }
696         if (value.external != null) {
697             sdata.charger = value.external.present;
698         }
699     }
700
701     private void postAlarms(@Nullable ArrayList<@Nullable String> errors) throws ShellyApiException {
702         if (errors != null) {
703             for (String e : errors) {
704                 if (e != null) {
705                     getThing().postEvent(e, false);
706                 }
707             }
708         }
709     }
710
711     protected @Nullable ArrayList<ShellySettingsInput> fillInputSettings(ShellyDeviceProfile profile,
712             Shelly2GetConfigResult dc) {
713         if (dc.input0 == null) {
714             return null; // device has no input
715         }
716
717         ArrayList<ShellySettingsInput> inputs = new ArrayList<>();
718         addInputSettings(inputs, dc.input0);
719         addInputSettings(inputs, dc.input1);
720         addInputSettings(inputs, dc.input2);
721         addInputSettings(inputs, dc.input3);
722         return inputs;
723     }
724
725     private void addInputSettings(ArrayList<ShellySettingsInput> inputs, @Nullable Shelly2DevConfigInput ic) {
726         if (ic == null) {
727             return;
728         }
729
730         ShellySettingsInput settings = new ShellySettingsInput();
731         settings.btnType = getString(ic.type).equalsIgnoreCase(SHELLY2_INPUTT_BUTTON) ? SHELLY_BTNT_MOMENTARY
732                 : SHELLY_BTNT_EDGE;
733         inputs.add(settings);
734     }
735
736     protected boolean updateInputStatus(ShellySettingsStatus status, Shelly2DeviceStatusResult ds,
737             boolean updateChannels) throws ShellyApiException {
738         boolean updated = false;
739         updated |= addInputStatus(status, ds.input0, updateChannels);
740         updated |= addInputStatus(status, ds.input1, updateChannels);
741         updated |= addInputStatus(status, ds.input2, updateChannels);
742         updated |= addInputStatus(status, ds.input3, updateChannels);
743         status.inputs = relayStatus.inputs;
744         return updated;
745     }
746
747     private boolean addInputStatus(ShellySettingsStatus status, @Nullable Shelly2InputStatus is, boolean updateChannels)
748             throws ShellyApiException {
749         if (is == null) {
750             return false;
751         }
752         ShellyDeviceProfile profile = getProfile();
753
754         if (is.id == null || is.id > profile.numInputs) {
755             logger.debug("{}: Invalid input id: {}", thingName, is.id);
756             return false;
757         }
758
759         String group = profile.getInputGroup(is.id);
760         ShellyInputState input = relayStatus.inputs.size() > is.id ? relayStatus.inputs.get(is.id)
761                 : new ShellyInputState();
762         boolean updated = false;
763         input.input = getBool(is.state) ? 1 : 0; // old format Integer, new one Boolean
764         if (input.event == null && profile.inButtonMode(is.id)) {
765             input.event = "";
766             input.eventCount = 0;
767         }
768         if (is.percent != null) { // analogous input
769             status.extAnalogInput = new ShellyExtAnalogInput(getDouble(is.percent));
770         }
771         relayStatus.inputs.set(is.id, input);
772         if (updateChannels) {
773             updated |= updateChannel(group, CHANNEL_INPUT + profile.getInputSuffix(is.id), getOnOff(getBool(is.state)));
774         }
775         return updated;
776     }
777
778     protected Shelly2RpcBaseMessage buildRequest(String method, @Nullable Object params) throws ShellyApiException {
779         Shelly2RpcBaseMessage request = new Shelly2RpcBaseMessage();
780         request.id = Math.abs(random.nextInt());
781         request.src = thingName;
782         request.method = !method.contains(".") ? SHELLYRPC_METHOD_CLASS_SHELLY + "." + method : method;
783         request.params = params;
784         request.auth = authReq;
785         return request;
786     }
787
788     protected String mapValue(Map<String, String> map, @Nullable String key) {
789         String value;
790         boolean known = key != null && !key.isEmpty() && map.containsKey(key);
791         value = known ? getString(map.get(key)) : "";
792         logger.trace("{}: API value {} was mapped to {}", thingName, key, known ? value : "UNKNOWN");
793         return value;
794     }
795
796     protected boolean updateChannel(String group, String channel, State value) throws ShellyApiException {
797         return getThing().updateChannel(group, channel, value);
798     }
799
800     protected ShellyThingInterface getThing() throws ShellyApiException {
801         ShellyThingInterface t = thing;
802         if (t != null) {
803             return t;
804         }
805         throw new ShellyApiException("Thing/profile not initialized!");
806     }
807
808     protected ShellyDeviceProfile getProfile() throws ShellyApiException {
809         if (thing != null) {
810             return thing.getProfile();
811         }
812         throw new ShellyApiException("Unable to get profile, thing not initialized!");
813     }
814 }