]> git.basschouten.com Git - openhab-addons.git/blob
2bc020c1841b8fb16d24307b3a79c29190c74bcf
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.wemo.internal.handler;
14
15 import static org.openhab.binding.wemo.internal.WemoBindingConstants.*;
16 import static org.openhab.binding.wemo.internal.WemoUtil.*;
17
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
20
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;
41
42 /**
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.
45  *
46  * @author Hans-Jörg Merk - Initial contribution
47  */
48 @NonNullByDefault
49 public class WemoLightHandler extends WemoBaseThingHandler {
50
51     private final Logger logger = LoggerFactory.getLogger(WemoLightHandler.class);
52
53     private final Object jobLock = new Object();
54
55     private @Nullable WemoBridgeHandler wemoBridgeHandler;
56
57     private @Nullable String wemoLightID;
58
59     private int currentBrightness;
60
61     /**
62      * Set dimming stepsize to 5%
63      */
64     private static final int DIM_STEPSIZE = 5;
65
66     /**
67      * The default refresh initial delay in Seconds.
68      */
69     private static final int DEFAULT_REFRESH_INITIAL_DELAY = 15;
70
71     private @Nullable ScheduledFuture<?> pollingJob;
72
73     public WemoLightHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpcaller) {
74         super(thing, upnpIOService, wemoHttpcaller);
75
76         logger.debug("Creating a WemoLightHandler for thing '{}'", getThing().getUID());
77     }
78
79     @Override
80     public void initialize() {
81         super.initialize();
82         // initialize() is only called if the required parameter 'deviceID' is available
83         wemoLightID = (String) getConfig().get(DEVICE_ID);
84
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.ONLINE);
91         } else {
92             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.BRIDGE_OFFLINE);
93         }
94     }
95
96     @Override
97     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
98         if (bridgeStatusInfo.getStatus().equals(ThingStatus.ONLINE)) {
99             updateStatus(ThingStatus.ONLINE);
100         } else {
101             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.BRIDGE_OFFLINE);
102             ScheduledFuture<?> job = this.pollingJob;
103             if (job != null && !job.isCancelled()) {
104                 job.cancel(true);
105             }
106             this.pollingJob = null;
107         }
108     }
109
110     @Override
111     public void dispose() {
112         logger.debug("WemoLightHandler disposed.");
113
114         ScheduledFuture<?> job = this.pollingJob;
115         if (job != null && !job.isCancelled()) {
116             job.cancel(true);
117         }
118         this.pollingJob = null;
119         super.dispose();
120     }
121
122     private synchronized @Nullable WemoBridgeHandler getWemoBridgeHandler() {
123         Bridge bridge = getBridge();
124         if (bridge == null) {
125             logger.warn("Required bridge not defined for device {}.", wemoLightID);
126             return null;
127         }
128         ThingHandler handler = bridge.getHandler();
129         if (handler instanceof WemoBridgeHandler) {
130             this.wemoBridgeHandler = (WemoBridgeHandler) handler;
131         } else {
132             logger.debug("No available bridge handler found for {} bridge {} .", wemoLightID, bridge.getUID());
133             return null;
134         }
135         return this.wemoBridgeHandler;
136     }
137
138     private void poll() {
139         synchronized (jobLock) {
140             if (pollingJob == null) {
141                 return;
142             }
143             try {
144                 logger.debug("Polling job");
145                 // Check if the Wemo device is set in the UPnP service registry
146                 // If not, set the thing state to ONLINE/CONFIG-PENDING and wait for the next poll
147                 if (!isUpnpDeviceRegistered()) {
148                     logger.debug("UPnP device {} not yet registered", getUDN());
149                     updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
150                             "@text/config-status.pending.device-not-registered [\"" + getUDN() + "\"]");
151                     return;
152                 }
153                 getDeviceState();
154             } catch (Exception e) {
155                 logger.debug("Exception during poll: {}", e.getMessage(), e);
156             }
157         }
158     }
159
160     @Override
161     public void handleCommand(ChannelUID channelUID, Command command) {
162         String wemoURL = getWemoURL(BASICACTION);
163         if (wemoURL == null) {
164             logger.debug("Failed to send command '{}' for device '{}': URL cannot be created", command,
165                     getThing().getUID());
166             return;
167         }
168         if (command instanceof RefreshType) {
169             try {
170                 getDeviceState();
171             } catch (Exception e) {
172                 logger.debug("Exception during poll", e);
173             }
174         } else {
175             Configuration configuration = getConfig();
176             configuration.get(DEVICE_ID);
177
178             WemoBridgeHandler wemoBridge = getWemoBridgeHandler();
179             if (wemoBridge == null) {
180                 logger.debug("wemoBridgeHandler not found, cannot handle command");
181                 return;
182             }
183             String devUDN = "uuid:" + wemoBridge.getThing().getConfiguration().get(UDN).toString();
184             logger.trace("WeMo Bridge to send command to : {}", devUDN);
185
186             String value = null;
187             String capability = null;
188             switch (channelUID.getId()) {
189                 case CHANNEL_BRIGHTNESS:
190                     capability = "10008";
191                     if (command instanceof PercentType) {
192                         int newBrightness = ((PercentType) command).intValue();
193                         logger.trace("wemoLight received Value {}", newBrightness);
194                         int value1 = Math.round(newBrightness * 255 / 100);
195                         value = value1 + ":0";
196                         currentBrightness = newBrightness;
197                     } else if (command instanceof OnOffType) {
198                         switch (command.toString()) {
199                             case "ON":
200                                 value = "255:0";
201                                 break;
202                             case "OFF":
203                                 value = "0:0";
204                                 break;
205                         }
206                     } else if (command instanceof IncreaseDecreaseType) {
207                         int newBrightness;
208                         switch (command.toString()) {
209                             case "INCREASE":
210                                 currentBrightness = currentBrightness + DIM_STEPSIZE;
211                                 newBrightness = Math.round(currentBrightness * 255 / 100);
212                                 if (newBrightness > 255) {
213                                     newBrightness = 255;
214                                 }
215                                 value = newBrightness + ":0";
216                                 break;
217                             case "DECREASE":
218                                 currentBrightness = currentBrightness - DIM_STEPSIZE;
219                                 newBrightness = Math.round(currentBrightness * 255 / 100);
220                                 if (newBrightness < 0) {
221                                     newBrightness = 0;
222                                 }
223                                 value = newBrightness + ":0";
224                                 break;
225                         }
226                     }
227                     break;
228                 case CHANNEL_STATE:
229                     capability = "10006";
230                     switch (command.toString()) {
231                         case "ON":
232                             value = "1";
233                             break;
234                         case "OFF":
235                             value = "0";
236                             break;
237                     }
238                     break;
239             }
240             try {
241                 if (capability != null && value != null) {
242                     String soapHeader = "\"urn:Belkin:service:bridge:1#SetDeviceStatus\"";
243                     String content = "<?xml version=\"1.0\"?>"
244                             + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
245                             + "<s:Body>" + "<u:SetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">"
246                             + "<DeviceStatusList>"
247                             + "&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;DeviceStatus&gt;&lt;DeviceID&gt;"
248                             + wemoLightID
249                             + "&lt;/DeviceID&gt;&lt;IsGroupAction&gt;NO&lt;/IsGroupAction&gt;&lt;CapabilityID&gt;"
250                             + capability + "&lt;/CapabilityID&gt;&lt;CapabilityValue&gt;" + value
251                             + "&lt;/CapabilityValue&gt;&lt;/DeviceStatus&gt;" + "</DeviceStatusList>"
252                             + "</u:SetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
253
254                     wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
255                     if ("10008".equals(capability)) {
256                         OnOffType binaryState = null;
257                         binaryState = "0".equals(value) ? OnOffType.OFF : OnOffType.ON;
258                         updateState(CHANNEL_STATE, binaryState);
259                     }
260                     updateStatus(ThingStatus.ONLINE);
261                 }
262             } catch (Exception e) {
263                 logger.warn("Failed to send command '{}' for device '{}': {}", command, getThing().getUID(),
264                         e.getMessage());
265                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
266             }
267         }
268     }
269
270     @Override
271     public @Nullable String getUDN() {
272         WemoBridgeHandler wemoBridge = getWemoBridgeHandler();
273         if (wemoBridge == null) {
274             logger.debug("wemoBridgeHandler not found");
275             return null;
276         }
277         return (String) wemoBridge.getThing().getConfiguration().get(UDN);
278     }
279
280     /**
281      * The {@link getDeviceState} is used for polling the actual state of a WeMo Light and updating the according
282      * channel states.
283      */
284     public void getDeviceState() {
285         logger.debug("Request actual state for LightID '{}'", wemoLightID);
286         String wemoURL = getWemoURL(BRIDGEACTION);
287         if (wemoURL == null) {
288             logger.debug("Failed to get actual state for device '{}': URL cannot be created", getThing().getUID());
289             return;
290         }
291         try {
292             String soapHeader = "\"urn:Belkin:service:bridge:1#GetDeviceStatus\"";
293             String content = "<?xml version=\"1.0\"?>"
294                     + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
295                     + "<s:Body>" + "<u:GetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceIDs>"
296                     + wemoLightID + "</DeviceIDs>" + "</u:GetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
297
298             String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
299             wemoCallResponse = unescapeXml(wemoCallResponse);
300             String response = substringBetween(wemoCallResponse, "<CapabilityValue>", "</CapabilityValue>");
301             logger.trace("wemoNewLightState = {}", response);
302             String[] splitResponse = response.split(",");
303             if (splitResponse[0] != null) {
304                 OnOffType binaryState = null;
305                 binaryState = "0".equals(splitResponse[0]) ? OnOffType.OFF : OnOffType.ON;
306                 updateState(CHANNEL_STATE, binaryState);
307             }
308             if (splitResponse[1] != null) {
309                 String splitBrightness[] = splitResponse[1].split(":");
310                 if (splitBrightness[0] != null) {
311                     int newBrightnessValue = Integer.valueOf(splitBrightness[0]);
312                     int newBrightness = Math.round(newBrightnessValue * 100 / 255);
313                     logger.trace("newBrightness = {}", newBrightness);
314                     State newBrightnessState = new PercentType(newBrightness);
315                     updateState(CHANNEL_BRIGHTNESS, newBrightnessState);
316                     currentBrightness = newBrightness;
317                 }
318             }
319             updateStatus(ThingStatus.ONLINE);
320         } catch (Exception e) {
321             logger.debug("Could not retrieve new Wemo light state for '{}':", getThing().getUID(), e);
322             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
323         }
324     }
325
326     @Override
327     public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
328         logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'",
329                 new Object[] { variable, value, service, this.getThing().getUID() });
330         String capabilityId = substringBetween(value, "<CapabilityId>", "</CapabilityId>");
331         String newValue = substringBetween(value, "<Value>", "</Value>");
332         switch (capabilityId) {
333             case "10006":
334                 OnOffType binaryState = null;
335                 binaryState = "0".equals(newValue) ? OnOffType.OFF : OnOffType.ON;
336                 updateState(CHANNEL_STATE, binaryState);
337                 break;
338             case "10008":
339                 String splitValue[] = newValue.split(":");
340                 if (splitValue[0] != null) {
341                     int newBrightnessValue = Integer.valueOf(splitValue[0]);
342                     int newBrightness = Math.round(newBrightnessValue * 100 / 255);
343                     State newBrightnessState = new PercentType(newBrightness);
344                     updateState(CHANNEL_BRIGHTNESS, newBrightnessState);
345                     currentBrightness = newBrightness;
346                 }
347                 break;
348         }
349     }
350 }