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;
22 import java.util.Random;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.openhab.binding.shelly.internal.api.ShellyApiException;
28 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
29 import org.openhab.binding.shelly.internal.api.ShellyHttpClient;
30 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyFavPos;
31 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
32 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyRollerStatus;
33 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySensorTmp;
34 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDimmer;
35 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsEMeter;
36 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsInput;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsMeter;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRoller;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortStatusRelay;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusRelay;
44 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor;
45 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtAnalogInput;
46 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtDigitalInput;
47 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtHumidity;
48 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtTemperature;
49 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtTemperature.ShellyShortTemp;
50 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellyExtVoltage;
51 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellySensorBat;
52 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellySensorHum;
53 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor.ShellySensorLux;
54 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2AuthRsp;
55 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DevConfigCover;
56 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DevConfigInput;
57 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DevConfigSwitch;
58 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2GetConfigResult;
59 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusLight;
60 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult;
61 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2CoverStatus;
62 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusEm;
63 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusHumidity;
64 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusIlluminance;
65 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusPower;
66 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusSmoke;
67 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult.Shelly2DeviceStatusTempId;
68 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2InputStatus;
69 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RelayStatus;
70 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcBaseMessage;
71 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2StatusEm1;
72 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
73 import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
74 import org.openhab.binding.shelly.internal.handler.ShellyComponents;
75 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
76 import org.openhab.core.types.State;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * {@link Shelly2ApiClient} Low level part of the RPC API
83 * @author Markus Michels - Initial contribution
86 public class Shelly2ApiClient extends ShellyHttpClient {
87 private final Logger logger = LoggerFactory.getLogger(Shelly2ApiClient.class);
88 protected final Random random = new Random();
89 protected final ShellyStatusRelay relayStatus = new ShellyStatusRelay();
90 protected final ShellyStatusSensor sensorData = new ShellyStatusSensor();
91 protected final ArrayList<ShellyRollerStatus> rollerStatus = new ArrayList<>();
92 protected @Nullable ShellyThingInterface thing;
93 protected @Nullable Shelly2AuthRsp authReq;
95 public Shelly2ApiClient(String thingName, ShellyThingInterface thing) {
96 super(thingName, thing);
100 public Shelly2ApiClient(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
101 super(thingName, config, httpClient);
104 protected static final Map<String, String> MAP_INMODE_BTNTYPE = Map.of(//
105 SHELLY2_BTNT_MOMENTARY, SHELLY_BTNT_MOMENTARY, //
106 SHELLY2_BTNT_FLIP, SHELLY_BTNT_TOGGLE, //
107 SHELLY2_BTNT_FOLLOW, SHELLY_BTNT_EDGE, //
108 SHELLY2_BTNT_DETACHED, SHELLY_BTNT_MOMENTARY);
110 protected static final Map<String, String> MAP_INPUT_EVENT_TYPE = Map.of(//
111 SHELLY2_EVENT_1PUSH, SHELLY_BTNEVENT_1SHORTPUSH, //
112 SHELLY2_EVENT_2PUSH, SHELLY_BTNEVENT_2SHORTPUSH, //
113 SHELLY2_EVENT_3PUSH, SHELLY_BTNEVENT_3SHORTPUSH, //
114 SHELLY2_EVENT_LPUSH, SHELLY_BTNEVENT_LONGPUSH, //
115 SHELLY2_EVENT_LSPUSH, SHELLY_BTNEVENT_LONGSHORTPUSH, //
116 SHELLY2_EVENT_SLPUSH, SHELLY_BTNEVENT_SHORTLONGPUSH);
118 protected static final Map<String, String> MAP_INPUT_EVENT_ID = Map.of(//
119 SHELLY2_EVENT_BTNUP, SHELLY_EVENT_BTN_OFF, //
120 SHELLY2_EVENT_BTNDOWN, SHELLY_EVENT_BTN_ON, //
121 SHELLY2_EVENT_1PUSH, SHELLY_EVENT_SHORTPUSH, //
122 SHELLY2_EVENT_2PUSH, SHELLY_EVENT_DOUBLE_SHORTPUSH, //
123 SHELLY2_EVENT_3PUSH, SHELLY_EVENT_TRIPLE_SHORTPUSH, //
124 SHELLY2_EVENT_LPUSH, SHELLY_EVENT_LONGPUSH, //
125 SHELLY2_EVENT_LSPUSH, SHELLY_EVENT_LONG_SHORTPUSH, //
126 SHELLY2_EVENT_SLPUSH, SHELLY_EVENT_SHORT_LONGTPUSH);
128 protected static final Map<String, String> MAP_INPUT_MODE = Map.of(//
129 SHELLY2_RMODE_SINGLE, SHELLY_INP_MODE_ONEBUTTON, //
130 SHELLY2_RMODE_DUAL, SHELLY_INP_MODE_OPENCLOSE, //
131 SHELLY2_RMODE_DETACHED, SHELLY_INP_MODE_ONEBUTTON);
133 protected static final Map<String, String> MAP_ROLLER_STATE = Map.of(//
134 SHELLY2_RSTATE_OPEN, SHELLY_RSTATE_OPEN, //
135 SHELLY2_RSTATE_CLOSED, SHELLY_RSTATE_CLOSE, //
136 SHELLY2_RSTATE_OPENING, SHELLY2_RSTATE_OPENING, // Gen2-only
137 SHELLY2_RSTATE_CLOSING, SHELLY2_RSTATE_CLOSING, // Gen2-only
138 SHELLY2_RSTATE_STOPPED, SHELLY_RSTATE_STOP, //
139 SHELLY2_RSTATE_CALIB, SHELLY2_RSTATE_CALIB); // Gen2-only
141 protected static final Map<String, String> MAP_PROFILE = Map.of(//
142 SHELLY_CLASS_RELAY, SHELLY2_PROFILE_RELAY, //
143 SHELLY_CLASS_ROLLER, SHELLY2_PROFILE_COVER);
145 protected @Nullable ArrayList<@Nullable ShellySettingsRelay> fillRelaySettings(ShellyDeviceProfile profile,
146 Shelly2GetConfigResult dc) {
147 ArrayList<@Nullable ShellySettingsRelay> relays = new ArrayList<>();
148 addRelaySettings(relays, dc.switch0);
149 addRelaySettings(relays, dc.switch1);
150 addRelaySettings(relays, dc.switch2);
151 addRelaySettings(relays, dc.switch3);
152 addRelaySettings(relays, dc.switch100);
153 return !relays.isEmpty() ? relays : null;
156 private void addRelaySettings(ArrayList<@Nullable ShellySettingsRelay> relays,
157 @Nullable Shelly2DevConfigSwitch cs) {
162 ShellySettingsRelay rsettings = new ShellySettingsRelay();
163 rsettings.id = cs.id;
164 rsettings.isValid = cs.id != null;
165 rsettings.name = cs.name;
166 rsettings.ison = false;
167 rsettings.autoOn = getBool(cs.autoOn) ? cs.autoOnDelay : 0;
168 rsettings.autoOff = getBool(cs.autoOff) ? cs.autoOffDelay : 0;
169 rsettings.hasTimer = false;
170 rsettings.btnType = mapValue(MAP_INMODE_BTNTYPE, getString(cs.mode).toLowerCase());
171 relays.add(rsettings);
174 protected boolean fillDeviceStatus(ShellySettingsStatus status, Shelly2DeviceStatusResult result,
175 boolean channelUpdate) throws ShellyApiException {
176 boolean updated = false;
178 if (result.temperature0 != null && result.temperature0.tC != null && !getProfile().isSensor) {
179 if (status.tmp == null) {
180 status.tmp = new ShellySensorTmp();
182 status.temperature = status.tmp.tC = result.temperature0.tC;
185 updated |= updateInputStatus(status, result, channelUpdate);
186 updated |= updateRelayStatus(status, result.switch0, channelUpdate);
187 updated |= updateRelayStatus(status, result.switch1, channelUpdate);
188 updated |= updateRelayStatus(status, result.switch2, channelUpdate);
189 updated |= updateRelayStatus(status, result.switch3, channelUpdate);
190 updated |= updateRelayStatus(status, result.switch100, channelUpdate);
191 updated |= updateRelayStatus(status, result.pm10, channelUpdate);
192 updated |= updateEmStatus(status, result.em0, channelUpdate);
193 updated |= updateEmStatus(status, result.em10, channelUpdate);
194 updated |= updateEmStatus(status, result.em11, channelUpdate);
195 updated |= updateRollerStatus(status, result.cover0, channelUpdate);
196 updated |= updateDimmerStatus(status, result.light0, channelUpdate);
198 updated |= ShellyComponents.updateMeters(getThing(), status);
201 updateHumidityStatus(sensorData, result.humidity0);
202 updateTemperatureStatus(sensorData, result.temperature0);
203 updateIlluminanceStatus(sensorData, result.illuminance0);
204 updateSmokeStatus(sensorData, result.smoke0);
205 updateBatteryStatus(sensorData, result.devicepower0);
206 updateAddonStatus(status, result);
207 updated |= ShellyComponents.updateSensors(getThing(), status);
211 private boolean updateRelayStatus(ShellySettingsStatus status, @Nullable Shelly2RelayStatus rs,
212 boolean channelUpdate) throws ShellyApiException {
216 ShellyDeviceProfile profile = getProfile();
218 ShellySettingsRelay rstatus;
219 ShellyShortStatusRelay sr;
220 int rIdx = getRelayIdx(profile, rs.id);
221 if (profile.hasRelays) {
223 throw new IllegalArgumentException("Update for invalid relay index");
225 rstatus = status.relays.get(rIdx);
226 sr = relayStatus.relays.get(rIdx);
228 rstatus = new ShellySettingsRelay();
229 sr = new ShellyShortStatusRelay();
233 sr.isValid = rstatus.isValid = true;
234 sr.name = rstatus.name = status.name;
235 if (rs.output != null) {
236 sr.ison = rstatus.ison = getBool(rs.output);
238 if (getDouble(rs.timerStartetAt) > 0) {
239 int duration = (int) (now() - rs.timerStartetAt);
240 sr.timerRemaining = duration;
242 if (status.tmp == null) {
243 status.tmp = new ShellySensorTmp();
245 if (rs.temperature != null) {
246 if (status.tmp == null) {
247 status.tmp = new ShellySensorTmp();
249 status.tmp.isValid = true;
250 status.tmp.tC = rs.temperature.tC;
251 status.tmp.tF = rs.temperature.tF;
252 status.tmp.units = "C";
253 sr.temperature = getDouble(rs.temperature.tC);
254 if (status.temperature == null || getDouble(rs.temperature.tC) > status.temperature) {
255 status.temperature = sr.temperature;
259 if (rs.errors != null) {
260 for (String error : rs.errors) {
261 sr.overpower = rstatus.overpower = SHELLY2_ERROR_OVERPOWER.equals(error);
262 status.overload = SHELLY2_ERROR_OVERVOLTAGE.equals(error);
263 status.overtemperature = SHELLY2_ERROR_OVERTEMP.equals(error);
265 sr.overtemperature = status.overtemperature;
268 ShellySettingsMeter sm = new ShellySettingsMeter();
269 ShellySettingsEMeter emeter = status.emeters != null ? status.emeters.get(rIdx) : new ShellySettingsEMeter();
270 if (rs.apower != null) {
271 sm.power = emeter.power = rs.apower;
273 if (rs.aenergy != null) {
274 // Gen2 reports Watt, needs to be converted to W/h
275 sm.total = emeter.total = rs.aenergy.total;
276 sm.counters = rs.aenergy.byMinute;
277 sm.timestamp = rs.aenergy.minuteTs;
279 if (rs.voltage != null) {
280 emeter.voltage = rs.voltage;
282 if (rs.current != null) {
283 emeter.current = rs.current;
289 if (profile.hasRelays) {
290 // Update internal structures
291 status.relays.set(rIdx, rstatus);
292 relayStatus.relays.set(rIdx, sr);
295 updateMeter(status, rIdx, sm, emeter, channelUpdate);
296 return channelUpdate && profile.hasRelays
297 ? ShellyComponents.updateRelay((ShellyBaseHandler) getThing(), status, rIdx)
301 private int getRelayIdx(ShellyDeviceProfile profile, @Nullable Integer id) {
302 if (id != null && profile.settings.relays != null) {
304 for (ShellySettingsRelay relay : profile.settings.relays) {
305 if (relay.isValid && relay.id != null && relay.id.intValue() == id.intValue()) {
314 private void updateMeter(ShellySettingsStatus status, int id, ShellySettingsMeter sm, ShellySettingsEMeter emeter,
315 boolean channelUpdate) throws ShellyApiException {
316 if (getProfile().numMeters == 0) {
319 sm.isValid = sm.power != null || sm.total != null;
320 emeter.isValid = emeter.current != null || emeter.voltage != null || emeter.power != null
321 || emeter.total != null;
322 status.meters.set(id, sm);
323 status.emeters.set(id, emeter);
324 relayStatus.meters.set(id, sm);
327 private boolean updateEmStatus(ShellySettingsStatus status, @Nullable Shelly2StatusEm1 em, boolean channelUpdate)
328 throws ShellyApiException {
333 ShellySettingsMeter sm = new ShellySettingsMeter();
334 ShellySettingsEMeter emeter = status.emeters.get(em.id);
335 if (em.actPower != null) {
336 sm.power = emeter.power = em.actPower;
338 if (em.aptrPower != null) {
339 emeter.totalReturned = em.aptrPower;
341 if (em.voltage != null) {
342 emeter.voltage = em.voltage;
344 if (em.current != null) {
345 emeter.current = em.current;
350 // Update internal structures
351 updateMeter(status, em.id, sm, emeter, channelUpdate);
353 postAlarms(em.errors);
354 return channelUpdate ? ShellyComponents.updateMeters(getThing(), status) : false;
357 private boolean updateEmStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusEm em,
358 boolean channelUpdate) throws ShellyApiException {
363 if (em.totalCurrent != null) {
364 status.totalCurrent = em.totalCurrent;
366 if (em.totalActPower != null) {
367 status.totalPower = em.totalActPower;
369 if (em.totalAprtPower != null) {
370 status.totalReturned = em.totalAprtPower;
373 ShellySettingsMeter sm = new ShellySettingsMeter();
374 ShellySettingsEMeter emeter = status.emeters.get(0);
375 if (em.aActPower != null) {
376 sm.power = emeter.power = em.aActPower;
378 if (em.aAprtPower != null) {
379 emeter.totalReturned = em.aAprtPower;
381 if (em.aVoltage != null) {
382 emeter.voltage = em.aVoltage;
384 if (em.aCurrent != null) {
385 emeter.current = em.aCurrent;
387 if (em.aPF != null) {
390 // Update internal structures
391 updateMeter(status, 0, sm, emeter, channelUpdate);
393 if (status.emeters.size() > 1) {
394 sm = new ShellySettingsMeter();
395 emeter = status.emeters.get(1);
396 sm.isValid = emeter.isValid = true;
397 if (em.bActPower != null) {
398 sm.power = emeter.power = em.bActPower;
400 if (em.bAprtPower != null) {
401 emeter.totalReturned = em.bAprtPower;
403 if (em.bVoltage != null) {
404 emeter.voltage = em.bVoltage;
406 if (em.bCurrent != null) {
407 emeter.current = em.bCurrent;
409 if (em.bPF != null) {
412 // Update internal structures
413 updateMeter(status, 1, sm, emeter, channelUpdate);
416 if (status.emeters.size() > 2) {
417 sm = new ShellySettingsMeter();
418 emeter = status.emeters.get(2);
419 sm.isValid = emeter.isValid = true;
420 if (em.cActPower != null) {
421 sm.power = emeter.power = em.cActPower;
423 if (em.cAprtPower != null) {
424 emeter.totalReturned = em.cAprtPower;
426 if (em.cVoltage != null) {
427 emeter.voltage = em.cVoltage;
429 if (em.cCurrent != null) {
430 emeter.current = em.cCurrent;
432 if (em.cPF != null) {
435 // Update internal structures
436 updateMeter(status, 2, sm, emeter, channelUpdate);
439 return channelUpdate ? ShellyComponents.updateMeters(getThing(), status) : false;
442 protected @Nullable ArrayList<@Nullable ShellySettingsRoller> fillRollerSettings(ShellyDeviceProfile profile,
443 Shelly2GetConfigResult dc) {
444 if (dc.cover0 == null) {
448 ArrayList<@Nullable ShellySettingsRoller> rollers = new ArrayList<>();
450 addRollerSettings(rollers, dc.cover0);
451 fillRollerFavorites(profile, dc);
455 private void addRollerSettings(ArrayList<@Nullable ShellySettingsRoller> rollers,
456 @Nullable Shelly2DevConfigCover coverConfig) {
457 if (coverConfig == null) {
461 ShellySettingsRoller settings = new ShellySettingsRoller();
462 settings.isValid = true;
463 settings.defaultState = coverConfig.initialState;
464 settings.inputMode = mapValue(MAP_INPUT_MODE, coverConfig.inMode);
465 settings.btnReverse = getBool(coverConfig.invertDirections) ? 1 : 0;
466 settings.swapInputs = coverConfig.swapInputs;
467 settings.maxtime = 0.0; // n/a
468 settings.maxtimeOpen = coverConfig.maxtimeOpen;
469 settings.maxtimeClose = coverConfig.maxtimeClose;
470 if (coverConfig.safetySwitch != null) {
471 settings.safetySwitch = coverConfig.safetySwitch.enable;
472 settings.safetyAction = coverConfig.safetySwitch.action;
474 if (coverConfig.obstructionDetection != null) {
475 settings.obstacleAction = coverConfig.obstructionDetection.action;
476 settings.obstacleDelay = coverConfig.obstructionDetection.holdoff.intValue();
477 settings.obstaclePower = coverConfig.obstructionDetection.powerThr;
479 rollers.add(settings);
482 private void fillRollerFavorites(ShellyDeviceProfile profile, Shelly2GetConfigResult dc) {
483 if (dc.sys.uiData.cover != null) {
484 String[] favorites = dc.sys.uiData.cover.split(",");
485 profile.settings.favorites = new ArrayList<>();
486 for (int i = 0; i < favorites.length; i++) {
487 ShellyFavPos fav = new ShellyFavPos();
488 fav.pos = Integer.parseInt(favorites[i]);
489 fav.name = fav.pos + "%";
490 profile.settings.favorites.add(fav);
492 profile.settings.favoritesEnabled = !profile.settings.favorites.isEmpty();
493 logger.debug("{}: Roller Favorites loaded: {}", thingName,
494 profile.settings.favoritesEnabled ? profile.settings.favorites.size() : "none");
498 private boolean updateRollerStatus(ShellySettingsStatus status, @Nullable Shelly2CoverStatus cs,
499 boolean updateChannels) throws ShellyApiException {
504 ShellyRollerStatus rs = status.rollers.get(cs.id);
505 ShellySettingsMeter sm = status.meters.get(cs.id);
506 ShellySettingsEMeter emeter = status.emeters.get(cs.id);
507 rs.isValid = sm.isValid = emeter.isValid = true;
508 if (cs.state != null) {
509 if (!getString(rs.state).equals(cs.state)) {
510 logger.debug("{}: Roller status changed from {} to {}, updateChannels={}", thingName, rs.state,
511 mapValue(MAP_ROLLER_STATE, cs.state), updateChannels);
513 rs.state = mapValue(MAP_ROLLER_STATE, cs.state);
514 rs.calibrating = SHELLY2_RSTATE_CALIB.equals(cs.state);
516 if (cs.currentPos != null) {
517 rs.currentPos = cs.currentPos;
519 if (cs.moveStartedAt != null) {
520 rs.duration = (int) (now() - cs.moveStartedAt.longValue());
522 if (cs.temperature != null && cs.temperature.tC > getDouble(status.temperature)) {
523 if (status.tmp == null) {
524 status.tmp = new ShellySensorTmp();
526 status.temperature = status.tmp.tC = getDouble(cs.temperature.tC);
528 if (cs.apower != null) {
529 rs.power = sm.power = emeter.power = cs.apower;
531 if (cs.aenergy != null) {
532 sm.total = emeter.total = cs.aenergy.total;
533 sm.counters = cs.aenergy.byMinute;
534 if (cs.aenergy.minuteTs != null) {
535 sm.timestamp = (long) cs.aenergy.minuteTs;
538 if (cs.voltage != null) {
539 emeter.voltage = cs.voltage;
541 if (cs.current != null) {
542 emeter.current = cs.current;
548 rollerStatus.set(cs.id, rs);
549 status.rollers.set(cs.id, rs);
550 relayStatus.meters.set(cs.id, sm);
551 status.meters.set(cs.id, sm);
552 status.emeters.set(cs.id, emeter);
554 postAlarms(cs.errors);
555 if (rs.calibrating != null && rs.calibrating) {
556 getThing().postEvent(SHELLY_EVENT_ROLLER_CALIB, false);
559 return updateChannels ? ShellyComponents.updateRoller((ShellyBaseHandler) getThing(), rs, cs.id) : false;
562 protected void fillDimmerSettings(ShellyDeviceProfile profile, Shelly2GetConfigResult dc) {
563 if (!profile.isDimmer || dc.light0 == null) {
567 if (profile.settings.dimmers != null) {
568 ShellySettingsDimmer ds = profile.settings.dimmers.get(0);
569 ds.autoOn = dc.light0.autoOnDelay;
570 ds.autoOff = dc.light0.autoOffDelay;
571 ds.name = dc.light0.name;
572 profile.settings.dimmers.set(0, ds);
576 private boolean updateDimmerStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusLight value,
577 boolean channelUpdate) throws ShellyApiException {
578 ShellyDeviceProfile profile = getProfile();
579 if (!profile.isDimmer || value == null) {
583 ShellyShortLightStatus ds = status.dimmers.get(0);
584 if (value.brightness != null) {
585 ds.brightness = value.brightness.intValue();
587 ds.ison = value.output;
588 ds.hasTimer = value.timerStartedAt != null;
589 ds.timerDuration = getDuration(value.timerStartedAt, value.timerDuration);
590 status.dimmers.set(0, ds);
591 return channelUpdate ? ShellyComponents.updateDimmers(getThing(), status) : false;
594 protected @Nullable Integer getDuration(@Nullable Double timerStartedAt, @Nullable Integer timerDuration) {
595 if (timerStartedAt == null || timerDuration == null) {
598 int duration = (int) (now() - timerStartedAt.longValue());
599 return duration <= timerDuration ? timerDuration - duration : 0;
603 private void updateAddonStatus(ShellySettingsStatus status, @Nullable Shelly2DeviceStatusResult ds)
604 throws ShellyApiException {
609 if (ds.temperature100 != null) {
610 if (status.extTemperature == null) {
611 status.extTemperature = new ShellyExtTemperature();
613 status.extTemperature.sensor1 = updateExtTempSensor(ds.temperature100);
614 status.extTemperature.sensor2 = updateExtTempSensor(ds.temperature101);
615 status.extTemperature.sensor3 = updateExtTempSensor(ds.temperature102);
616 status.extTemperature.sensor4 = updateExtTempSensor(ds.temperature103);
617 status.extTemperature.sensor5 = updateExtTempSensor(ds.temperature104);
619 if (ds.humidity100 != null) {
620 status.extHumidity = new ShellyExtHumidity(ds.humidity100.rh);
622 if (ds.voltmeter100 != null) {
623 status.extVoltage = new ShellyExtVoltage(ds.voltmeter100.voltage);
625 if (ds.input100 != null) {
626 status.extDigitalInput = new ShellyExtDigitalInput(getBool(ds.input100.state));
630 private @Nullable ShellyShortTemp updateExtTempSensor(@Nullable Shelly2DeviceStatusTempId value) {
632 ShellyShortTemp temp = new ShellyShortTemp();
633 temp.hwID = value.id.toString();
641 protected void updateHumidityStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusHumidity value) {
645 if (sdata.hum == null) {
646 sdata.hum = new ShellySensorHum();
648 sdata.hum.value = getDouble(value.rh);
651 protected void updateTemperatureStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusTempId value) {
655 if (sdata.tmp == null) {
656 sdata.tmp = new ShellySensorTmp();
658 sdata.tmp.isValid = true;
659 sdata.tmp.units = SHELLY_TEMP_CELSIUS;
660 sdata.tmp.tC = value.tC;
661 sdata.tmp.tF = value.tF;
664 protected void updateIlluminanceStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusIlluminance value) {
668 if (sdata.lux == null) {
669 sdata.lux = new ShellySensorLux();
671 sdata.lux.isValid = value.lux != null;
672 sdata.lux.value = value.lux;
673 sdata.lux.illumination = value.illumination;
676 protected void updateSmokeStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusSmoke value) {
680 sdata.smoke = getBool(value.alarm);
681 sdata.mute = getBool(value.mute);
684 protected void updateBatteryStatus(ShellyStatusSensor sdata, @Nullable Shelly2DeviceStatusPower value) {
688 if (sdata.bat == null) {
689 sdata.bat = new ShellySensorBat();
692 if (value.battery != null) {
693 sdata.bat.voltage = value.battery.volt;
694 sdata.bat.value = value.battery.percent;
696 if (value.external != null) {
697 sdata.charger = value.external.present;
701 private void postAlarms(@Nullable ArrayList<@Nullable String> errors) throws ShellyApiException {
702 if (errors != null) {
703 for (String e : errors) {
705 getThing().postEvent(e, false);
711 protected @Nullable ArrayList<ShellySettingsInput> fillInputSettings(ShellyDeviceProfile profile,
712 Shelly2GetConfigResult dc) {
713 if (dc.input0 == null) {
714 return null; // device has no input
717 ArrayList<ShellySettingsInput> inputs = new ArrayList<>();
718 addInputSettings(inputs, dc.input0);
719 addInputSettings(inputs, dc.input1);
720 addInputSettings(inputs, dc.input2);
721 addInputSettings(inputs, dc.input3);
725 private void addInputSettings(ArrayList<ShellySettingsInput> inputs, @Nullable Shelly2DevConfigInput ic) {
730 ShellySettingsInput settings = new ShellySettingsInput();
731 settings.btnType = getString(ic.type).equalsIgnoreCase(SHELLY2_INPUTT_BUTTON) ? SHELLY_BTNT_MOMENTARY
733 inputs.add(settings);
736 protected boolean updateInputStatus(ShellySettingsStatus status, Shelly2DeviceStatusResult ds,
737 boolean updateChannels) throws ShellyApiException {
738 boolean updated = false;
739 updated |= addInputStatus(status, ds.input0, updateChannels);
740 updated |= addInputStatus(status, ds.input1, updateChannels);
741 updated |= addInputStatus(status, ds.input2, updateChannels);
742 updated |= addInputStatus(status, ds.input3, updateChannels);
743 status.inputs = relayStatus.inputs;
747 private boolean addInputStatus(ShellySettingsStatus status, @Nullable Shelly2InputStatus is, boolean updateChannels)
748 throws ShellyApiException {
752 ShellyDeviceProfile profile = getProfile();
754 if (is.id == null || is.id > profile.numInputs) {
755 logger.debug("{}: Invalid input id: {}", thingName, is.id);
759 String group = profile.getInputGroup(is.id);
760 ShellyInputState input = relayStatus.inputs.size() > is.id ? relayStatus.inputs.get(is.id)
761 : new ShellyInputState();
762 boolean updated = false;
763 input.input = getBool(is.state) ? 1 : 0; // old format Integer, new one Boolean
764 if (input.event == null && profile.inButtonMode(is.id)) {
766 input.eventCount = 0;
768 if (is.percent != null) { // analogous input
769 status.extAnalogInput = new ShellyExtAnalogInput(getDouble(is.percent));
771 relayStatus.inputs.set(is.id, input);
772 if (updateChannels) {
773 updated |= updateChannel(group, CHANNEL_INPUT + profile.getInputSuffix(is.id), getOnOff(getBool(is.state)));
778 protected Shelly2RpcBaseMessage buildRequest(String method, @Nullable Object params) throws ShellyApiException {
779 Shelly2RpcBaseMessage request = new Shelly2RpcBaseMessage();
780 request.id = Math.abs(random.nextInt());
781 request.src = thingName;
782 request.method = !method.contains(".") ? SHELLYRPC_METHOD_CLASS_SHELLY + "." + method : method;
783 request.params = params;
784 request.auth = authReq;
788 protected String mapValue(Map<String, String> map, @Nullable String key) {
790 boolean known = key != null && !key.isEmpty() && map.containsKey(key);
791 value = known ? getString(map.get(key)) : "";
792 logger.trace("{}: API value {} was mapped to {}", thingName, key, known ? value : "UNKNOWN");
796 protected boolean updateChannel(String group, String channel, State value) throws ShellyApiException {
797 return getThing().updateChannel(group, channel, value);
800 protected ShellyThingInterface getThing() throws ShellyApiException {
801 ShellyThingInterface t = thing;
805 throw new ShellyApiException("Thing/profile not initialized!");
808 protected ShellyDeviceProfile getProfile() throws ShellyApiException {
810 return thing.getProfile();
812 throw new ShellyApiException("Unable to get profile, thing not initialized!");