2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.api2;
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.*;
20 import java.util.ArrayList;
21 import java.util.HashMap;
23 import java.util.Random;
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;
83 * {@link Shelly2ApiClient} Low level part of the RPC API
85 * @author Markus Michels - Initial contribution
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;
97 public Shelly2ApiClient(String thingName, ShellyThingInterface thing) {
98 super(thingName, thing);
102 public Shelly2ApiClient(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
103 super(thingName, config, httpClient);
106 protected static final Map<String, String> MAP_INMODE_BTNTYPE = new HashMap<>();
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);
114 protected static final Map<String, String> MAP_INPUT_EVENT_TYPE = new HashMap<>();
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);
124 protected static final Map<String, String> MAP_INPUT_EVENT_ID = new HashMap<>();
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);
136 protected static final Map<String, String> MAP_INPUT_MODE = new HashMap<>();
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);
143 protected static final Map<String, String> MAP_ROLLER_STATE = new HashMap<>();
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
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;
164 private void addRelaySettings(ArrayList<@Nullable ShellySettingsRelay> relays,
165 @Nullable Shelly2DevConfigSwitch cs) {
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);
182 protected boolean fillDeviceStatus(ShellySettingsStatus status, Shelly2DeviceStatusResult result,
183 boolean channelUpdate) throws ShellyApiException {
184 boolean updated = false;
186 if (result.temperature0 != null && result.temperature0.tC != null && !getProfile().isSensor) {
187 if (status.tmp == null) {
188 status.tmp = new ShellySensorTmp();
190 status.temperature = status.tmp.tC = result.temperature0.tC;
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);
206 updated |= ShellyComponents.updateMeters(getThing(), status);
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);
219 private boolean updateRelayStatus(ShellySettingsStatus status, @Nullable Shelly2RelayStatus rs,
220 boolean channelUpdate) throws ShellyApiException {
224 ShellyDeviceProfile profile = getProfile();
226 ShellySettingsRelay rstatus;
227 ShellyShortStatusRelay sr;
228 int rIdx = getRelayIdx(profile, rs.id);
229 if (profile.hasRelays) {
231 throw new IllegalArgumentException("Update for invalid relay index");
233 rstatus = status.relays.get(rIdx);
234 sr = relayStatus.relays.get(rIdx);
236 rstatus = new ShellySettingsRelay();
237 sr = new ShellyShortStatusRelay();
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);
246 if (getDouble(rs.timerStartetAt) > 0) {
247 int duration = (int) (now() - rs.timerStartetAt);
248 sr.timerRemaining = duration;
250 if (status.tmp == null) {
251 status.tmp = new ShellySensorTmp();
253 if (rs.temperature != null) {
254 if (status.tmp == null) {
255 status.tmp = new ShellySensorTmp();
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;
267 if (rs.voltage != null) {
268 if (status.voltage == null || rs.voltage > status.voltage) {
269 status.voltage = rs.voltage;
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);
278 sr.overtemperature = status.overtemperature;
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;
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;
292 if (rs.voltage != null) {
293 emeter.voltage = rs.voltage;
295 if (rs.current != null) {
296 emeter.current = rs.current;
302 if (profile.hasRelays) {
303 // Update internal structures
304 status.relays.set(rIdx, rstatus);
305 relayStatus.relays.set(rIdx, sr);
308 updateMeter(status, rIdx, sm, emeter, channelUpdate);
309 return channelUpdate && profile.hasRelays
310 ? ShellyComponents.updateRelay((ShellyBaseHandler) getThing(), status, rIdx)
314 private int getRelayIdx(ShellyDeviceProfile profile, @Nullable Integer id) {
315 if (id != null && profile.settings.relays != null) {
317 for (ShellySettingsRelay relay : profile.settings.relays) {
318 if (relay.isValid && relay.id != null && relay.id.intValue() == id.intValue()) {
327 private void updateMeter(ShellySettingsStatus status, int id, ShellySettingsMeter sm, ShellySettingsEMeter emeter,
328 boolean channelUpdate) throws ShellyApiException {
329 if (getProfile().numMeters == 0) {
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);
339 private boolean updateEmStatus(ShellySettingsStatus status, @Nullable Shelly2StatusEm1 em, boolean channelUpdate)
340 throws ShellyApiException {
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;
350 if (em.aptrPower != null) {
351 emeter.totalReturned = em.aptrPower;
353 if (em.voltage != null) {
354 emeter.voltage = em.voltage;
356 if (em.current != null) {
357 emeter.current = em.current;
362 // Update internal structures
363 updateMeter(status, em.id, sm, emeter, channelUpdate);
365 postAlarms(em.errors);
366 return channelUpdate ? ShellyComponents.updateMeters(getThing(), status) : false;
369 private boolean updateEmStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusEm em,
370 boolean channelUpdate) throws ShellyApiException {
375 if (em.totalCurrent != null) {
376 status.totalCurrent = em.totalCurrent;
378 if (em.totalActPower != null) {
379 status.totalPower = em.totalActPower;
381 if (em.totalAprtPower != null) {
382 status.totalReturned = em.totalAprtPower;
385 ShellySettingsMeter sm = new ShellySettingsMeter();
386 ShellySettingsEMeter emeter = status.emeters.get(0);
387 if (em.aActPower != null) {
388 sm.power = emeter.power = em.aActPower;
390 if (em.aAprtPower != null) {
391 emeter.totalReturned = em.aAprtPower;
393 if (em.aVoltage != null) {
394 emeter.voltage = em.aVoltage;
396 if (em.aCurrent != null) {
397 emeter.current = em.aCurrent;
399 if (em.aPF != null) {
402 // Update internal structures
403 updateMeter(status, 0, sm, emeter, channelUpdate);
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;
412 if (em.bAprtPower != null) {
413 emeter.totalReturned = em.bAprtPower;
415 if (em.bVoltage != null) {
416 emeter.voltage = em.bVoltage;
418 if (em.bCurrent != null) {
419 emeter.current = em.bCurrent;
421 if (em.bPF != null) {
424 // Update internal structures
425 updateMeter(status, 1, sm, emeter, channelUpdate);
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;
435 if (em.cAprtPower != null) {
436 emeter.totalReturned = em.cAprtPower;
438 if (em.cVoltage != null) {
439 emeter.voltage = em.cVoltage;
441 if (em.cCurrent != null) {
442 emeter.current = em.cCurrent;
444 if (em.cPF != null) {
447 // Update internal structures
448 updateMeter(status, 2, sm, emeter, channelUpdate);
451 return channelUpdate ? ShellyComponents.updateMeters(getThing(), status) : false;
454 protected @Nullable ArrayList<@Nullable ShellySettingsRoller> fillRollerSettings(ShellyDeviceProfile profile,
455 Shelly2GetConfigResult dc) {
456 if (dc.cover0 == null) {
460 ArrayList<@Nullable ShellySettingsRoller> rollers = new ArrayList<>();
462 addRollerSettings(rollers, dc.cover0);
463 fillRollerFavorites(profile, dc);
467 private void addRollerSettings(ArrayList<@Nullable ShellySettingsRoller> rollers,
468 @Nullable Shelly2DevConfigCover coverConfig) {
469 if (coverConfig == null) {
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;
486 if (coverConfig.obstructionDetection != null) {
487 settings.obstacleAction = coverConfig.obstructionDetection.action;
488 settings.obstacleDelay = coverConfig.obstructionDetection.holdoff.intValue();
489 settings.obstaclePower = coverConfig.obstructionDetection.powerThr;
491 rollers.add(settings);
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);
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");
510 private boolean updateRollerStatus(ShellySettingsStatus status, @Nullable Shelly2CoverStatus cs,
511 boolean updateChannels) throws ShellyApiException {
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);
525 rs.state = mapValue(MAP_ROLLER_STATE, cs.state);
526 rs.calibrating = SHELLY2_RSTATE_CALIB.equals(cs.state);
528 if (cs.currentPos != null) {
529 rs.currentPos = cs.currentPos;
531 if (cs.moveStartedAt != null) {
532 rs.duration = (int) (now() - cs.moveStartedAt.longValue());
534 if (cs.temperature != null && cs.temperature.tC > getDouble(status.temperature)) {
535 if (status.tmp == null) {
536 status.tmp = new ShellySensorTmp();
538 status.temperature = status.tmp.tC = getDouble(cs.temperature.tC);
540 if (cs.apower != null) {
541 rs.power = sm.power = emeter.power = cs.apower;
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;
550 if (cs.voltage != null) {
551 if (status.voltage == null || cs.voltage > status.voltage) {
552 status.voltage = cs.voltage;
554 emeter.voltage = cs.voltage;
556 if (cs.current != null) {
557 emeter.current = cs.current;
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);
569 postAlarms(cs.errors);
570 if (rs.calibrating != null && rs.calibrating) {
571 getThing().postEvent(SHELLY_EVENT_ROLLER_CALIB, false);
574 return updateChannels ? ShellyComponents.updateRoller((ShellyBaseHandler) getThing(), rs, cs.id) : false;
577 protected void fillDimmerSettings(ShellyDeviceProfile profile, Shelly2GetConfigResult dc) {
578 if (!profile.isDimmer || dc.light0 == null) {
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);
591 private boolean updateDimmerStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusLight value,
592 boolean channelUpdate) throws ShellyApiException {
593 ShellyDeviceProfile profile = getProfile();
594 if (!profile.isDimmer || value == null) {
598 ShellyShortLightStatus ds = status.dimmers.get(0);
599 if (value.brightness != null) {
600 ds.brightness = value.brightness.intValue();
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;
609 protected @Nullable Integer getDuration(@Nullable Double timerStartedAt, @Nullable Integer timerDuration) {
610 if (timerStartedAt == null || timerDuration == null) {
613 int duration = (int) (now() - timerStartedAt.longValue());
614 return duration <= timerDuration ? timerDuration - duration : 0;
618 private void updateAddonStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusResult ds)
619 throws ShellyApiException {
624 if (ds.temperature100 != null) {
625 if (status.extTemperature == null) {
626 status.extTemperature = new ShellyExtTemperature();
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);
634 if (ds.humidity100 != null) {
635 status.extHumidity = new ShellyExtHumidity(ds.humidity100.rh);
637 if (ds.voltmeter100 != null) {
638 status.extVoltage = new ShellyExtVoltage(ds.voltmeter100.voltage);
640 if (ds.input100 != null) {
641 status.extDigitalInput = new ShellyExtDigitalInput(getBool(ds.input100.state));
645 private @Nullable ShellyShortTemp updateExtTempSensor(@Nullable Shelly2DeviceStatusTempId value) {
647 ShellyShortTemp temp = new ShellyShortTemp();
648 temp.hwID = value.id.toString();
656 protected void updateHumidityStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusHumidity value) {
660 if (sdata.hum == null) {
661 sdata.hum = new ShellySensorHum();
663 sdata.hum.value = getDouble(value.rh);
666 protected void updateTemperatureStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusTempId value) {
670 if (sdata.tmp == null) {
671 sdata.tmp = new ShellySensorTmp();
673 sdata.tmp.isValid = true;
674 sdata.tmp.units = SHELLY_TEMP_CELSIUS;
675 sdata.tmp.tC = value.tC;
676 sdata.tmp.tF = value.tF;
679 protected void updateIlluminanceStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusIlluminance value) {
683 if (sdata.lux == null) {
684 sdata.lux = new ShellySensorLux();
686 sdata.lux.isValid = value.lux != null;
687 sdata.lux.value = value.lux;
688 sdata.lux.illumination = value.illumination;
691 protected void updateSmokeStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusSmoke value) {
695 sdata.smoke = getBool(value.alarm);
696 sdata.mute = getBool(value.mute);
699 protected void updateBatteryStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusPower value) {
703 if (sdata.bat == null) {
704 sdata.bat = new ShellySensorBat();
707 if (value.battery != null) {
708 sdata.bat.voltage = value.battery.volt;
709 sdata.bat.value = value.battery.percent;
711 if (value.external != null) {
712 sdata.charger = value.external.present;
716 private void postAlarms(@Nullable ArrayList<@Nullable String> errors) throws ShellyApiException {
717 if (errors != null) {
718 for (String e : errors) {
720 getThing().postEvent(e, false);
726 protected @Nullable ArrayList<ShellySettingsInput> fillInputSettings(ShellyDeviceProfile profile,
727 Shelly2GetConfigResult dc) {
728 if (dc.input0 == null) {
729 return null; // device has no input
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);
740 private void addInputSettings(ArrayList<ShellySettingsInput> inputs, @Nullable Shelly2DevConfigInput ic) {
745 ShellySettingsInput settings = new ShellySettingsInput();
746 settings.btnType = getString(ic.type).equalsIgnoreCase(SHELLY2_INPUTT_BUTTON) ? SHELLY_BTNT_MOMENTARY
748 inputs.add(settings);
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;
762 private boolean addInputStatus(ShellySettingsStatus status, @Nullable Shelly2InputStatus is, boolean updateChannels)
763 throws ShellyApiException {
767 ShellyDeviceProfile profile = getProfile();
769 if (is.id == null || is.id > profile.numInputs) {
770 logger.debug("{}: Invalid input id: {}", thingName, is.id);
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)) {
781 input.eventCount = 0;
783 if (is.percent != null) { // analogous input
784 status.extAnalogInput = new ShellyExtAnalogInput(getDouble(is.percent));
786 relayStatus.inputs.set(is.id, input);
787 if (updateChannels) {
788 updated |= updateChannel(group, CHANNEL_INPUT + profile.getInputSuffix(is.id), getOnOff(getBool(is.state)));
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;
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);
820 protected String mapValue(Map<String, String> map, @Nullable String key) {
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");
828 protected boolean updateChannel(String group, String channel, State value) throws ShellyApiException {
829 return getThing().updateChannel(group, channel, value);
832 protected ShellyThingInterface getThing() throws ShellyApiException {
833 ShellyThingInterface t = thing;
837 throw new ShellyApiException("Thing/profile not initialized!");
840 protected ShellyDeviceProfile getProfile() throws ShellyApiException {
842 return thing.getProfile();
844 throw new ShellyApiException("Unable to get profile, thing not initialized!");