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