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.handler;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jetty.client.HttpClient;
21 import org.openhab.binding.shelly.internal.api.ShellyApiException;
22 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
23 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyRollerStatus;
24 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDimmer;
25 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
26 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
27 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
28 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
29 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
30 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
31 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
32 import org.openhab.core.library.types.DecimalType;
33 import org.openhab.core.library.types.IncreaseDecreaseType;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.PercentType;
36 import org.openhab.core.library.types.StopMoveType;
37 import org.openhab.core.library.types.UpDownType;
38 import org.openhab.core.library.unit.Units;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.types.Command;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 import com.google.gson.Gson;
48 * The{@link ShellyRelayHandler} handles light (bulb+rgbw2) specific commands and status. All other commands will be
49 * handled by the generic thing handler.
51 * @author Markus Michels - Initial contribution
54 public class ShellyRelayHandler extends ShellyBaseHandler {
55 private final Logger logger = LoggerFactory.getLogger(ShellyRelayHandler.class);
60 * @param thing The thing passed by the HandlerFactory
61 * @param bindingConfig configuration of the binding
62 * @param coapServer coap server instance
63 * @param localIP local IP of the openHAB host
64 * @param httpPort port of the openHAB HTTP API
66 public ShellyRelayHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
67 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
68 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
69 super(thing, translationProvider, bindingConfig, thingTable, coapServer, httpClient);
73 public void initialize() {
78 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
80 String groupName = getString(channelUID.getGroupId());
82 if (groupName.startsWith(CHANNEL_GROUP_RELAY_CONTROL)
83 && groupName.length() > CHANNEL_GROUP_RELAY_CONTROL.length()) {
84 rIndex = Integer.parseInt(substringAfter(channelUID.getGroupId(), CHANNEL_GROUP_RELAY_CONTROL)) - 1;
85 } else if (groupName.startsWith(CHANNEL_GROUP_ROL_CONTROL)
86 && groupName.length() > CHANNEL_GROUP_ROL_CONTROL.length()) {
87 rIndex = Integer.parseInt(substringAfter(channelUID.getGroupId(), CHANNEL_GROUP_ROL_CONTROL)) - 1;
90 switch (channelUID.getIdWithoutGroup()) {
95 if (!profile.isRoller) {
96 // extract relay number of group name (relay0->0, relay1->1...)
97 logger.debug("{}: Set relay output to {}", thingName, command);
98 api.setRelayTurn(rIndex, command == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
100 logger.debug("{}: Device is in roller mode, channel command {} ignored", thingName, channelUID);
103 case CHANNEL_BRIGHTNESS: // e.g.Dimmer, Duo
104 handleBrightness(command, rIndex);
107 case CHANNEL_ROL_CONTROL_POS:
108 case CHANNEL_ROL_CONTROL_CONTROL:
109 logger.debug("{}: Roller command/position {}", thingName, command);
110 handleRoller(command, groupName, rIndex,
111 channelUID.getIdWithoutGroup().equals(CHANNEL_ROL_CONTROL_CONTROL));
113 // request updates the next 45sec to update roller position after it stopped
114 if (!autoCoIoT && !profile.isGen2) {
115 requestUpdates(45 / UPDATE_STATUS_INTERVAL_SECONDS, false);
119 case CHANNEL_ROL_CONTROL_FAV:
120 if (command instanceof Number) {
121 int id = ((Number) command).intValue() - 1;
122 int pos = profile.getRollerFav(id);
124 logger.debug("{}: Selecting favorite {}, position = {}", thingName, id, pos);
125 api.setRollerPos(rIndex, pos);
129 logger.debug("{}: Invalid favorite index: {}", thingName, command);
132 case CHANNEL_TIMER_AUTOON:
133 logger.debug("{}: Set Auto-ON timer to {}", thingName, command);
134 api.setAutoTimer(rIndex, SHELLY_TIMER_AUTOON, getNumber(command).doubleValue());
136 case CHANNEL_TIMER_AUTOOFF:
137 logger.debug("{}: Set Auto-OFF timer to {}", thingName, command);
138 api.setAutoTimer(rIndex, SHELLY_TIMER_AUTOOFF, getNumber(command).doubleValue());
145 * Brightness channel has 2 functions: Switch On/Off (OnOnType) and setting brightness (PercentType)
146 * There is some more logic in the control. When brightness is set to 0 the control sends also an OFF command
147 * When current brightness is 0 and slider will be moved the new brightness will be set, but also an ON command is
152 * @throws ShellyApiException
154 private void handleBrightness(Command command, Integer index) throws ShellyApiException {
156 if (command instanceof PercentType) { // Dimmer
157 value = ((PercentType) command).intValue();
158 } else if (command instanceof DecimalType) { // Number
159 value = ((DecimalType) command).intValue();
160 } else if (command instanceof OnOffType) { // Switch
161 logger.debug("{}: Switch output {}", thingName, command);
162 updateBrightnessChannel(index, (OnOffType) command, value);
164 } else if (command instanceof IncreaseDecreaseType) {
165 ShellyShortLightStatus light = api.getLightStatus(index);
166 if (command == IncreaseDecreaseType.INCREASE) {
167 value = Math.min(light.brightness + DIM_STEPSIZE, 100);
169 value = Math.max(light.brightness - DIM_STEPSIZE, 0);
171 logger.debug("{}: Increase/Decrease brightness from {} to {}", thingName, light.brightness, value);
173 validateRange("brightness", value, 0, 100);
175 // Switch light off on brightness = 0
177 logger.debug("{}: Brightness=0 -> switch output OFF", thingName);
178 updateBrightnessChannel(index, OnOffType.OFF, 0);
180 logger.debug("{}: Setting dimmer brightness to {}", thingName, value);
181 updateBrightnessChannel(index, OnOffType.ON, value);
185 private void updateBrightnessChannel(int lightId, OnOffType power, int brightness) throws ShellyApiException {
186 updateChannel(CHANNEL_COLOR_WHITE, CHANNEL_BRIGHTNESS + "$Switch", power);
187 if (brightness > 0) {
188 api.setBrightness(lightId, brightness, config.brightnessAutoOn);
190 api.setRelayTurn(lightId, power == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
191 if (brightness >= 0) { // ignore -1
192 updateChannel(CHANNEL_COLOR_WHITE, CHANNEL_BRIGHTNESS + "$Value",
193 toQuantityType((double) (power == OnOffType.ON ? brightness : 0), DIGITS_NONE, Units.PERCENT));
199 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
200 // map status to channels
201 boolean updated = false;
202 updated |= updateRelays(status);
203 updated |= updateDimmers(status);
204 updated |= updateLed(status);
209 * Handle Roller Commands
211 * @param command from handleCommand()
212 * @param groupName relay, roller...
213 * @param index relay number
214 * @param isControl true: is the Rollershutter channel, false: rollerpos channel
215 * @throws ShellyApiException
217 private void handleRoller(Command command, String groupName, Integer index, boolean isControl)
218 throws ShellyApiException {
221 if ((command instanceof UpDownType) || (command instanceof OnOffType)) {
222 ShellyRollerStatus rstatus = api.getRollerStatus(index);
224 if (!getString(rstatus.state).isEmpty() && !getString(rstatus.state).equals(SHELLY_ALWD_ROLLER_TURN_STOP)) {
225 if ((command == UpDownType.UP && getString(rstatus.state).equals(SHELLY_ALWD_ROLLER_TURN_OPEN))
226 || (command == UpDownType.DOWN
227 && getString(rstatus.state).equals(SHELLY_ALWD_ROLLER_TURN_CLOSE))) {
228 logger.debug("{}: Roller is already in requested position ({}), ignore command {}", thingName,
229 getString(rstatus.state), command);
230 requestUpdates(1, false);
235 if (command == UpDownType.UP || command == OnOffType.ON
236 || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 100))) {
237 logger.debug("{}: Open roller", thingName);
238 int shpos = profile.getRollerFav(config.favoriteUP - 1);
240 logger.debug("{}: Use favoriteUP id {} for positioning roller({}%)", thingName, config.favoriteUP,
242 api.setRollerPos(index, shpos);
245 api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_OPEN);
247 } else if (command == UpDownType.DOWN || command == OnOffType.OFF
248 || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 0))) {
249 logger.debug("{}: Closing roller", thingName);
250 int shpos = profile.getRollerFav(config.favoriteDOWN - 1);
252 // use favorite position
253 logger.debug("{}: Use favoriteDOWN id {} for positioning roller ({}%)", thingName,
254 config.favoriteDOWN, shpos);
255 api.setRollerPos(index, shpos);
258 api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_CLOSE);
261 } else if (command == StopMoveType.STOP) {
262 logger.debug("{}: Stop roller", thingName);
263 api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_STOP);
265 logger.debug("{}: Set roller to position {}", thingName, command);
266 if (command instanceof PercentType) {
267 PercentType p = (PercentType) command;
268 position = p.intValue();
269 } else if (command instanceof DecimalType) {
270 DecimalType d = (DecimalType) command;
271 position = d.intValue();
273 throw new IllegalArgumentException(
274 "Invalid value type for roller control/position" + command.getClass().toString());
277 // take position from RollerShutter control and map to Shelly positon
278 // OH: 0=closed, 100=open; Shelly 0=open, 100=closed)
279 // take position 1:1 from position channel
280 position = isControl ? SHELLY_MAX_ROLLER_POS - position : position;
281 validateRange("roller position", position, SHELLY_MIN_ROLLER_POS, SHELLY_MAX_ROLLER_POS);
283 logger.debug("{}: Changing roller position to {}", thingName, position);
284 api.setRollerPos(index, position);
289 * Auto-create relay channels depending on relay type/mode
291 private void createRelayChannels(ShellySettingsRelay relay, int idx) {
292 if (!areChannelsCreated()) {
293 updateChannelDefinitions(ShellyChannelDefinitions.createRelayChannels(getThing(), profile, relay, idx));
297 private void createDimmerChannels(ShellySettingsStatus dstatus, int idx) {
298 if (!areChannelsCreated()) {
299 updateChannelDefinitions(ShellyChannelDefinitions.createDimmerChannels(getThing(), profile, dstatus, idx));
303 private void createRollerChannels(ShellyRollerStatus roller) {
304 if (!areChannelsCreated()) {
305 updateChannelDefinitions(ShellyChannelDefinitions.createRollerChannels(getThing(), roller));
310 * Update Relay/Roller channels
312 * @param th Thing Handler instance
313 * @param profile ShellyDeviceProfile
314 * @param status Last ShellySettingsStatus
316 * @throws ShellyApiException
318 public boolean updateRelays(ShellySettingsStatus status) throws ShellyApiException {
319 boolean updated = false;
320 if (profile.hasRelays && !profile.isDimmer) {
322 if (status.voltage == null && profile.settings.supplyVoltage != null) {
323 // Shelly 1PM/1L (fix)
324 voltage = profile.settings.supplyVoltage == 0 ? 110.0 : 220.0;
326 // Shelly 2.5 (measured)
327 voltage = getDouble(status.voltage);
330 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_VOLTAGE,
331 toQuantityType(voltage, DIGITS_VOLT, Units.VOLT));
334 if (!profile.isRoller) {
335 logger.trace("{}: Updating {} relay(s)", thingName, profile.numRelays);
336 for (int i = 0; i < status.relays.size(); i++) {
337 createRelayChannels(status.relays.get(i), i);
338 updated |= ShellyComponents.updateRelay(this, status, i);
341 // Check for Relay in Roller Mode
342 logger.trace("{}: Updating {} rollers", thingName, profile.numRollers);
343 for (int i = 0; i < profile.numRollers; i++) {
344 ShellyRollerStatus roller = status.rollers.get(i);
345 createRollerChannels(roller);
346 updated |= ShellyComponents.updateRoller(this, roller, i);
354 * Update Relay/Roller channels
356 * @param th Thing Handler instance
357 * @param profile ShellyDeviceProfile
358 * @param status Last ShellySettingsStatus
360 * @throws ShellyApiException
362 public boolean updateDimmers(ShellySettingsStatus orgStatus) throws ShellyApiException {
363 boolean updated = false;
364 if (profile.isDimmer) {
365 // We need to fixup the returned Json: The dimmer returns light[] element, which is ok, but it doesn't have
366 // the same structure as lights[] from Bulb,RGBW2 and Duo. The tag gets replaced by dimmers[] so that Gson
367 // maps to a different structure (ShellyShortLight).
368 Gson gson = new Gson();
369 ShellySettingsStatus dstatus = fromJson(gson, Shelly1ApiJsonDTO.fixDimmerJson(orgStatus.json),
370 ShellySettingsStatus.class);
372 logger.trace("{}: Updating {} dimmers(s)", thingName, dstatus.dimmers.size());
374 for (ShellyShortLightStatus dimmer : dstatus.dimmers) {
376 String groupName = profile.numRelays <= 1 ? CHANNEL_GROUP_DIMMER_CONTROL
377 : CHANNEL_GROUP_DIMMER_CONTROL + r.toString();
379 createDimmerChannels(dstatus, l);
381 // On a status update we map a dimmer.ison = false to brightness 0 rather than the device's brightness
382 // and send an OFF status to the same channel.
383 // When the device's brightness is > 0 we send the new value to the channel and an ON command
385 updated |= updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Switch", OnOffType.ON);
386 updated |= updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Value",
387 toQuantityType((double) getInteger(dimmer.brightness), DIGITS_NONE, Units.PERCENT));
389 updated |= updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Switch", OnOffType.OFF);
390 updated |= updateChannel(groupName, CHANNEL_BRIGHTNESS + "$Value",
391 toQuantityType(0.0, DIGITS_NONE, Units.PERCENT));
394 if (profile.settings.dimmers != null) {
395 ShellySettingsDimmer dsettings = profile.settings.dimmers.get(l);
396 if (dsettings != null) {
397 updated |= updateChannel(groupName, CHANNEL_TIMER_AUTOON,
398 toQuantityType(getDouble(dsettings.autoOn), Units.SECOND));
399 updated |= updateChannel(groupName, CHANNEL_TIMER_AUTOOFF,
400 toQuantityType(getDouble(dsettings.autoOff), Units.SECOND));
411 * Update LED channels
413 * @param th Thing Handler instance
414 * @param profile ShellyDeviceProfile
415 * @param status Last ShellySettingsStatus
417 public boolean updateLed(ShellySettingsStatus status) {
418 boolean updated = false;
419 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_LED_STATUS_DISABLE,
420 getOnOff(profile.settings.ledStatusDisable));
421 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_LED_POWER_DISABLE,
422 getOnOff(profile.settings.ledPowerDisable));