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.wemo.internal.handler;
15 import static org.openhab.binding.wemo.internal.WemoBindingConstants.*;
16 import static org.openhab.binding.wemo.internal.WemoUtil.*;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.wemo.internal.http.WemoHttpCall;
24 import org.openhab.core.config.core.Configuration;
25 import org.openhab.core.io.transport.upnp.UpnpIOService;
26 import org.openhab.core.library.types.IncreaseDecreaseType;
27 import org.openhab.core.library.types.OnOffType;
28 import org.openhab.core.library.types.PercentType;
29 import org.openhab.core.thing.Bridge;
30 import org.openhab.core.thing.ChannelUID;
31 import org.openhab.core.thing.Thing;
32 import org.openhab.core.thing.ThingStatus;
33 import org.openhab.core.thing.ThingStatusDetail;
34 import org.openhab.core.thing.ThingStatusInfo;
35 import org.openhab.core.thing.binding.ThingHandler;
36 import org.openhab.core.types.Command;
37 import org.openhab.core.types.RefreshType;
38 import org.openhab.core.types.State;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * {@link WemoLightHandler} is the handler for a WeMo light, responsible for handling commands and state updates for the
44 * different channels of a WeMo light.
46 * @author Hans-Jörg Merk - Initial contribution
49 public class WemoLightHandler extends WemoBaseThingHandler {
51 private final Logger logger = LoggerFactory.getLogger(WemoLightHandler.class);
53 private final Object jobLock = new Object();
55 private @Nullable WemoBridgeHandler wemoBridgeHandler;
57 private @Nullable String wemoLightID;
59 private int currentBrightness;
62 * Set dimming stepsize to 5%
64 private static final int DIM_STEPSIZE = 5;
67 * The default refresh initial delay in Seconds.
69 private static final int DEFAULT_REFRESH_INITIAL_DELAY = 15;
71 private @Nullable ScheduledFuture<?> pollingJob;
73 public WemoLightHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpcaller) {
74 super(thing, upnpIOService, wemoHttpcaller);
76 logger.debug("Creating a WemoLightHandler for thing '{}'", getThing().getUID());
80 public void initialize() {
82 // initialize() is only called if the required parameter 'deviceID' is available
83 wemoLightID = (String) getConfig().get(DEVICE_ID);
85 final Bridge bridge = getBridge();
86 if (bridge != null && bridge.getStatus() == ThingStatus.ONLINE) {
87 addSubscription(BRIDGEEVENT);
88 pollingJob = scheduler.scheduleWithFixedDelay(this::poll, DEFAULT_REFRESH_INITIAL_DELAY,
89 DEFAULT_REFRESH_INTERVAL_SECONDS, TimeUnit.SECONDS);
90 updateStatus(ThingStatus.UNKNOWN);
92 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.BRIDGE_OFFLINE);
97 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
98 if (bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) {
99 updateStatus(ThingStatus.ONLINE);
101 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
102 ScheduledFuture<?> job = this.pollingJob;
103 if (job != null && !job.isCancelled()) {
106 this.pollingJob = null;
111 public void dispose() {
112 logger.debug("WemoLightHandler disposed.");
114 ScheduledFuture<?> job = this.pollingJob;
115 if (job != null && !job.isCancelled()) {
118 this.pollingJob = null;
122 private synchronized @Nullable WemoBridgeHandler getWemoBridgeHandler() {
123 Bridge bridge = getBridge();
124 if (bridge == null) {
125 logger.warn("Required bridge not defined for device {}.", wemoLightID);
128 ThingHandler handler = bridge.getHandler();
129 if (handler instanceof WemoBridgeHandler) {
130 this.wemoBridgeHandler = (WemoBridgeHandler) handler;
132 logger.debug("No available bridge handler found for {} bridge {} .", wemoLightID, bridge.getUID());
135 return this.wemoBridgeHandler;
138 private void poll() {
139 synchronized (jobLock) {
140 if (pollingJob == null) {
144 logger.debug("Polling job");
145 // Check if the Wemo device is set in the UPnP service registry
146 if (!isUpnpDeviceRegistered()) {
147 logger.debug("UPnP device {} not yet registered", getUDN());
148 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
149 "@text/config-status.pending.device-not-registered [\"" + getUDN() + "\"]");
153 } catch (Exception e) {
154 logger.debug("Exception during poll: {}", e.getMessage(), e);
160 public void handleCommand(ChannelUID channelUID, Command command) {
161 String wemoURL = getWemoURL(BASICACTION);
162 if (wemoURL == null) {
163 logger.debug("Failed to send command '{}' for device '{}': URL cannot be created", command,
164 getThing().getUID());
167 if (command instanceof RefreshType) {
170 } catch (Exception e) {
171 logger.debug("Exception during poll", e);
174 Configuration configuration = getConfig();
175 configuration.get(DEVICE_ID);
177 WemoBridgeHandler wemoBridge = getWemoBridgeHandler();
178 if (wemoBridge == null) {
179 logger.debug("wemoBridgeHandler not found, cannot handle command");
182 String devUDN = "uuid:" + wemoBridge.getThing().getConfiguration().get(UDN).toString();
183 logger.trace("WeMo Bridge to send command to : {}", devUDN);
186 String capability = null;
187 switch (channelUID.getId()) {
188 case CHANNEL_BRIGHTNESS:
189 capability = "10008";
190 if (command instanceof PercentType) {
191 int newBrightness = ((PercentType) command).intValue();
192 logger.trace("wemoLight received Value {}", newBrightness);
193 int value1 = Math.round(newBrightness * 255 / 100);
194 value = value1 + ":0";
195 currentBrightness = newBrightness;
196 } else if (command instanceof OnOffType) {
197 switch (command.toString()) {
205 } else if (command instanceof IncreaseDecreaseType) {
207 switch (command.toString()) {
209 currentBrightness = currentBrightness + DIM_STEPSIZE;
210 newBrightness = Math.round(currentBrightness * 255 / 100);
211 if (newBrightness > 255) {
214 value = newBrightness + ":0";
217 currentBrightness = currentBrightness - DIM_STEPSIZE;
218 newBrightness = Math.round(currentBrightness * 255 / 100);
219 if (newBrightness < 0) {
222 value = newBrightness + ":0";
228 capability = "10006";
229 switch (command.toString()) {
240 if (capability != null && value != null) {
241 String soapHeader = "\"urn:Belkin:service:bridge:1#SetDeviceStatus\"";
242 String content = "<?xml version=\"1.0\"?>"
243 + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
244 + "<s:Body>" + "<u:SetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">"
245 + "<DeviceStatusList>"
246 + "<?xml version="1.0" encoding="UTF-8"?><DeviceStatus><DeviceID>"
248 + "</DeviceID><IsGroupAction>NO</IsGroupAction><CapabilityID>"
249 + capability + "</CapabilityID><CapabilityValue>" + value
250 + "</CapabilityValue></DeviceStatus>" + "</DeviceStatusList>"
251 + "</u:SetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
253 wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
254 if ("10008".equals(capability)) {
255 OnOffType binaryState = null;
256 binaryState = "0".equals(value) ? OnOffType.OFF : OnOffType.ON;
257 updateState(CHANNEL_STATE, binaryState);
259 updateStatus(ThingStatus.ONLINE);
261 } catch (Exception e) {
262 logger.warn("Failed to send command '{}' for device '{}': {}", command, getThing().getUID(),
264 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
270 public @Nullable String getUDN() {
271 WemoBridgeHandler wemoBridge = getWemoBridgeHandler();
272 if (wemoBridge == null) {
273 logger.debug("wemoBridgeHandler not found");
276 return (String) wemoBridge.getThing().getConfiguration().get(UDN);
280 * The {@link getDeviceState} is used for polling the actual state of a WeMo Light and updating the according
283 public void getDeviceState() {
284 logger.debug("Request actual state for LightID '{}'", wemoLightID);
285 String wemoURL = getWemoURL(BRIDGEACTION);
286 if (wemoURL == null) {
287 logger.debug("Failed to get actual state for device '{}': URL cannot be created", getThing().getUID());
291 String soapHeader = "\"urn:Belkin:service:bridge:1#GetDeviceStatus\"";
292 String content = "<?xml version=\"1.0\"?>"
293 + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
294 + "<s:Body>" + "<u:GetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceIDs>"
295 + wemoLightID + "</DeviceIDs>" + "</u:GetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
297 String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
298 wemoCallResponse = unescapeXml(wemoCallResponse);
299 String response = substringBetween(wemoCallResponse, "<CapabilityValue>", "</CapabilityValue>");
300 logger.trace("wemoNewLightState = {}", response);
301 String[] splitResponse = response.split(",");
302 if (splitResponse[0] != null) {
303 OnOffType binaryState = null;
304 binaryState = "0".equals(splitResponse[0]) ? OnOffType.OFF : OnOffType.ON;
305 updateState(CHANNEL_STATE, binaryState);
307 if (splitResponse[1] != null) {
308 String splitBrightness[] = splitResponse[1].split(":");
309 if (splitBrightness[0] != null) {
310 int newBrightnessValue = Integer.valueOf(splitBrightness[0]);
311 int newBrightness = Math.round(newBrightnessValue * 100 / 255);
312 logger.trace("newBrightness = {}", newBrightness);
313 State newBrightnessState = new PercentType(newBrightness);
314 updateState(CHANNEL_BRIGHTNESS, newBrightnessState);
315 currentBrightness = newBrightness;
318 updateStatus(ThingStatus.ONLINE);
319 } catch (Exception e) {
320 logger.debug("Could not retrieve new Wemo light state for '{}':", getThing().getUID(), e);
321 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
326 public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
327 logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'",
328 new Object[] { variable, value, service, this.getThing().getUID() });
329 String capabilityId = substringBetween(value, "<CapabilityId>", "</CapabilityId>");
330 String newValue = substringBetween(value, "<Value>", "</Value>");
331 switch (capabilityId) {
333 OnOffType binaryState = null;
334 binaryState = "0".equals(newValue) ? OnOffType.OFF : OnOffType.ON;
335 updateState(CHANNEL_STATE, binaryState);
338 String splitValue[] = newValue.split(":");
339 if (splitValue[0] != null) {
340 int newBrightnessValue = Integer.valueOf(splitValue[0]);
341 int newBrightness = Math.round(newBrightnessValue * 100 / 255);
342 State newBrightnessState = new PercentType(newBrightness);
343 updateState(CHANNEL_BRIGHTNESS, newBrightnessState);
344 currentBrightness = newBrightness;