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