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.ShellyRollerStatus;
23 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
24 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
25 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
26 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
27 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
28 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
29 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
30 import org.openhab.core.library.types.DecimalType;
31 import org.openhab.core.library.types.IncreaseDecreaseType;
32 import org.openhab.core.library.types.OnOffType;
33 import org.openhab.core.library.types.PercentType;
34 import org.openhab.core.library.types.StopMoveType;
35 import org.openhab.core.library.types.UpDownType;
36 import org.openhab.core.library.unit.Units;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.types.Command;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * The{@link ShellyRelayHandler} handles light (bulb+rgbw2) specific commands and status. All other commands will be
45 * handled by the generic thing handler.
47 * @author Markus Michels - Initial contribution
50 public class ShellyRelayHandler extends ShellyBaseHandler {
51 private final Logger logger = LoggerFactory.getLogger(ShellyRelayHandler.class);
56 * @param thing The thing passed by the HandlerFactory
57 * @param bindingConfig configuration of the binding
58 * @param coapServer coap server instance
59 * @param localIP local IP of the openHAB host
60 * @param httpPort port of the openHAB HTTP API
62 public ShellyRelayHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
63 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
64 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
65 super(thing, translationProvider, bindingConfig, thingTable, coapServer, httpClient);
69 public void initialize() {
74 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
76 String groupName = getString(channelUID.getGroupId());
78 if (groupName.startsWith(CHANNEL_GROUP_RELAY_CONTROL)
79 && groupName.length() > CHANNEL_GROUP_RELAY_CONTROL.length()) {
80 rIndex = Integer.parseInt(substringAfter(channelUID.getGroupId(), CHANNEL_GROUP_RELAY_CONTROL)) - 1;
81 } else if (groupName.startsWith(CHANNEL_GROUP_ROL_CONTROL)
82 && groupName.length() > CHANNEL_GROUP_ROL_CONTROL.length()) {
83 rIndex = Integer.parseInt(substringAfter(channelUID.getGroupId(), CHANNEL_GROUP_ROL_CONTROL)) - 1;
86 switch (channelUID.getIdWithoutGroup()) {
91 if (!profile.isRoller) {
92 // extract relay number of group name (relay0->0, relay1->1...)
93 logger.debug("{}: Set relay output to {}", thingName, command);
94 api.setRelayTurn(rIndex, command == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
96 logger.debug("{}: Device is in roller mode, channel command {} ignored", thingName, channelUID);
99 case CHANNEL_BRIGHTNESS: // e.g.Dimmer, Duo
100 handleBrightness(command, rIndex);
103 case CHANNEL_ROL_CONTROL_POS:
104 case CHANNEL_ROL_CONTROL_CONTROL:
105 logger.debug("{}: Roller command/position {}", thingName, command);
106 handleRoller(command, groupName, rIndex,
107 channelUID.getIdWithoutGroup().equals(CHANNEL_ROL_CONTROL_CONTROL));
109 // request updates the next 45sec to update roller position after it stopped
110 if (!autoCoIoT && !profile.isGen2) {
111 requestUpdates(45 / UPDATE_STATUS_INTERVAL_SECONDS, false);
115 case CHANNEL_ROL_CONTROL_FAV:
116 if (command instanceof Number) {
117 int id = ((Number) command).intValue() - 1;
118 int pos = profile.getRollerFav(id);
120 logger.debug("{}: Selecting favorite {}, position = {}", thingName, id, pos);
121 api.setRollerPos(rIndex, pos);
125 logger.debug("{}: Invalid favorite index: {}", thingName, command);
128 case CHANNEL_TIMER_AUTOON:
129 logger.debug("{}: Set Auto-ON timer to {}", thingName, command);
130 api.setAutoTimer(rIndex, SHELLY_TIMER_AUTOON, getNumber(command).doubleValue());
132 case CHANNEL_TIMER_AUTOOFF:
133 logger.debug("{}: Set Auto-OFF timer to {}", thingName, command);
134 api.setAutoTimer(rIndex, SHELLY_TIMER_AUTOOFF, getNumber(command).doubleValue());
136 case CHANNEL_EMETER_RESETTOTAL:
137 String id = substringAfter(groupName, CHANNEL_GROUP_METER);
138 int mIdx = id.isEmpty() ? 0 : Integer.parseInt(id) - 1;
139 logger.debug("{}: Reset Meter Totals for meter {}", thingName, mIdx + 1);
140 api.resetMeterTotal(mIdx); // currently there is only 1 emdata component
141 updateChannel(groupName, CHANNEL_EMETER_RESETTOTAL, OnOffType.OFF);
148 * Brightness channel has 2 functions: Switch On/Off (OnOnType) and setting brightness (PercentType)
149 * There is some more logic in the control. When brightness is set to 0 the control sends also an OFF command
150 * When current brightness is 0 and slider will be moved the new brightness will be set, but also an ON command is
155 * @throws ShellyApiException
157 private void handleBrightness(Command command, Integer index) throws ShellyApiException {
159 if (command instanceof PercentType) { // Dimmer
160 value = ((PercentType) command).intValue();
161 } else if (command instanceof DecimalType) { // Number
162 value = ((DecimalType) command).intValue();
163 } else if (command instanceof OnOffType) { // Switch
164 logger.debug("{}: Switch output {}", thingName, command);
165 updateBrightnessChannel(index, (OnOffType) command, value);
167 } else if (command instanceof IncreaseDecreaseType) {
168 ShellyShortLightStatus light = api.getLightStatus(index);
169 if (command == IncreaseDecreaseType.INCREASE) {
170 value = Math.min(light.brightness + DIM_STEPSIZE, 100);
172 value = Math.max(light.brightness - DIM_STEPSIZE, 0);
174 logger.debug("{}: Increase/Decrease brightness from {} to {}", thingName, light.brightness, value);
176 validateRange("brightness", value, 0, 100);
178 // Switch light off on brightness = 0
180 logger.debug("{}: Brightness=0 -> switch output OFF", thingName);
181 updateBrightnessChannel(index, OnOffType.OFF, 0);
183 logger.debug("{}: Setting dimmer brightness to {}", thingName, value);
184 updateBrightnessChannel(index, OnOffType.ON, value);
188 private void updateBrightnessChannel(int lightId, OnOffType power, int brightness) throws ShellyApiException {
189 updateChannel(CHANNEL_COLOR_WHITE, CHANNEL_BRIGHTNESS + "$Switch", power);
190 if (brightness > 0) {
191 api.setBrightness(lightId, brightness, config.brightnessAutoOn);
193 api.setLightTurn(lightId, power == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
194 if (brightness >= 0) { // ignore -1
195 updateChannel(CHANNEL_COLOR_WHITE, CHANNEL_BRIGHTNESS + "$Value",
196 toQuantityType((double) (power == OnOffType.ON ? brightness : 0), DIGITS_NONE, Units.PERCENT));
202 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
203 // map status to channels
204 boolean updated = false;
205 updated |= updateRelays(status);
206 updated |= ShellyComponents.updateDimmers(this, status);
207 updated |= updateLed(status);
212 * Handle Roller Commands
214 * @param command from handleCommand()
215 * @param groupName relay, roller...
216 * @param index relay number
217 * @param isControl true: is the Rollershutter channel, false: rollerpos channel
218 * @throws ShellyApiException
220 private void handleRoller(Command command, String groupName, Integer index, boolean isControl)
221 throws ShellyApiException {
224 if ((command instanceof UpDownType) || (command instanceof OnOffType)) {
225 ShellyRollerStatus rstatus = api.getRollerStatus(index);
227 if (!getString(rstatus.state).isEmpty() && !getString(rstatus.state).equals(SHELLY_ALWD_ROLLER_TURN_STOP)) {
228 if ((command == UpDownType.UP && getString(rstatus.state).equals(SHELLY_ALWD_ROLLER_TURN_OPEN))
229 || (command == UpDownType.DOWN
230 && getString(rstatus.state).equals(SHELLY_ALWD_ROLLER_TURN_CLOSE))) {
231 logger.debug("{}: Roller is already in requested position ({}), ignore command {}", thingName,
232 getString(rstatus.state), command);
233 requestUpdates(1, false);
238 if (command == UpDownType.UP || command == OnOffType.ON
239 || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 100))) {
240 logger.debug("{}: Open roller", thingName);
241 int shpos = profile.getRollerFav(config.favoriteUP - 1);
243 logger.debug("{}: Use favoriteUP id {} for positioning roller({}%)", thingName, config.favoriteUP,
245 api.setRollerPos(index, shpos);
248 api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_OPEN);
250 } else if (command == UpDownType.DOWN || command == OnOffType.OFF
251 || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 0))) {
252 logger.debug("{}: Closing roller", thingName);
253 int shpos = profile.getRollerFav(config.favoriteDOWN - 1);
255 // use favorite position
256 logger.debug("{}: Use favoriteDOWN id {} for positioning roller ({}%)", thingName,
257 config.favoriteDOWN, shpos);
258 api.setRollerPos(index, shpos);
261 api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_CLOSE);
264 } else if (command == StopMoveType.STOP) {
265 logger.debug("{}: Stop roller", thingName);
266 api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_STOP);
268 logger.debug("{}: Set roller to position {}", thingName, command);
269 if (command instanceof PercentType) {
270 PercentType p = (PercentType) command;
271 position = p.intValue();
272 } else if (command instanceof DecimalType) {
273 DecimalType d = (DecimalType) command;
274 position = d.intValue();
276 throw new IllegalArgumentException(
277 "Invalid value type for roller control/position" + command.getClass().toString());
280 // take position from RollerShutter control and map to Shelly positon
281 // OH: 0=closed, 100=open; Shelly 0=open, 100=closed)
282 // take position 1:1 from position channel
283 position = isControl ? SHELLY_MAX_ROLLER_POS - position : position;
284 validateRange("roller position", position, SHELLY_MIN_ROLLER_POS, SHELLY_MAX_ROLLER_POS);
286 logger.debug("{}: Changing roller position to {}", thingName, position);
287 api.setRollerPos(index, position);
292 * Auto-create relay channels depending on relay type/mode
294 private void createRelayChannels(ShellySettingsRelay relay, int idx) {
295 if (!areChannelsCreated()) {
296 updateChannelDefinitions(ShellyChannelDefinitions.createRelayChannels(getThing(), profile, relay, idx));
300 private void createRollerChannels(ShellyRollerStatus roller) {
301 if (!areChannelsCreated()) {
302 updateChannelDefinitions(ShellyChannelDefinitions.createRollerChannels(getThing(), roller));
307 * Update Relay/Roller channels
309 * @param th Thing Handler instance
310 * @param profile ShellyDeviceProfile
311 * @param status Last ShellySettingsStatus
313 * @throws ShellyApiException
315 public boolean updateRelays(ShellySettingsStatus status) throws ShellyApiException {
316 boolean updated = false;
317 if (profile.hasRelays && !profile.isDimmer) {
319 if (status.voltage == null && profile.settings.supplyVoltage != null) {
320 // Shelly 1PM/1L (fix)
321 voltage = profile.settings.supplyVoltage == 0 ? 110.0 : 220.0;
323 // Shelly 2.5 (measured)
324 voltage = getDouble(status.voltage);
327 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_VOLTAGE,
328 toQuantityType(voltage, DIGITS_VOLT, Units.VOLT));
331 if (!profile.isRoller) {
332 logger.trace("{}: Updating {} relay(s)", thingName, profile.numRelays);
333 for (int i = 0; i < status.relays.size(); i++) {
334 createRelayChannels(status.relays.get(i), i);
335 updated |= ShellyComponents.updateRelay(this, status, i);
338 // Check for Relay in Roller Mode
339 logger.trace("{}: Updating {} rollers", thingName, profile.numRollers);
340 for (int i = 0; i < profile.numRollers; i++) {
341 ShellyRollerStatus roller = status.rollers.get(i);
342 createRollerChannels(roller);
343 updated |= ShellyComponents.updateRoller(this, roller, i);
351 * Update LED channels
353 * @param th Thing Handler instance
354 * @param profile ShellyDeviceProfile
355 * @param status Last ShellySettingsStatus
357 public boolean updateLed(ShellySettingsStatus status) {
358 boolean updated = false;
359 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_LED_STATUS_DISABLE,
360 getOnOff(profile.settings.ledStatusDisable));
361 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_LED_POWER_DISABLE,
362 getOnOff(profile.settings.ledPowerDisable));