]> git.basschouten.com Git - openhab-addons.git/blob
ada6c3b9903c3f8c41491b252cd456029c47950f
[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.io.StringReader;
19 import java.util.Collections;
20 import java.util.Set;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.wemo.internal.http.WemoHttpCall;
30 import org.openhab.core.config.core.Configuration;
31 import org.openhab.core.io.transport.upnp.UpnpIOService;
32 import org.openhab.core.library.types.OnOffType;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingStatusDetail;
37 import org.openhab.core.thing.ThingTypeUID;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.RefreshType;
40 import org.openhab.core.types.State;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.NodeList;
46 import org.xml.sax.InputSource;
47
48 /**
49  * The {@link WemoMakerHandler} is responsible for handling commands, which are
50  * sent to one of the channels and to update their states.
51  *
52  * @author Hans-Jörg Merk - Initial contribution
53  */
54 @NonNullByDefault
55 public class WemoMakerHandler extends WemoBaseThingHandler {
56
57     private final Logger logger = LoggerFactory.getLogger(WemoMakerHandler.class);
58
59     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MAKER);
60
61     private final Object jobLock = new Object();
62
63     private @Nullable ScheduledFuture<?> pollingJob;
64
65     public WemoMakerHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpcaller) {
66         super(thing, upnpIOService, wemoHttpcaller);
67
68         logger.debug("Creating a WemoMakerHandler for thing '{}'", getThing().getUID());
69     }
70
71     @Override
72     public void initialize() {
73         super.initialize();
74         Configuration configuration = getConfig();
75
76         if (configuration.get(UDN) != null) {
77             logger.debug("Initializing WemoMakerHandler for UDN '{}'", configuration.get(UDN));
78             host = getHost();
79             pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, DEFAULT_REFRESH_INTERVAL_SECONDS,
80                     TimeUnit.SECONDS);
81             updateStatus(ThingStatus.ONLINE);
82         } else {
83             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
84                     "@text/config-status.error.missing-udn");
85             logger.debug("Cannot initalize WemoMakerHandler. UDN not set.");
86         }
87     }
88
89     @Override
90     public void dispose() {
91         logger.debug("WemoMakerHandler disposed.");
92
93         ScheduledFuture<?> job = this.pollingJob;
94         if (job != null && !job.isCancelled()) {
95             job.cancel(true);
96         }
97         this.pollingJob = null;
98         super.dispose();
99     }
100
101     private void poll() {
102         synchronized (jobLock) {
103             if (pollingJob == null) {
104                 return;
105             }
106             try {
107                 logger.debug("Polling job");
108                 host = getHost();
109                 // Check if the Wemo device is set in the UPnP service registry
110                 // If not, set the thing state to ONLINE/CONFIG-PENDING and wait for the next poll
111                 if (!isUpnpDeviceRegistered()) {
112                     logger.debug("UPnP device {} not yet registered", getUDN());
113                     updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
114                             "@text/config-status.pending.device-not-registered [\"" + getUDN() + "\"]");
115                     return;
116                 }
117                 updateWemoState();
118             } catch (Exception e) {
119                 logger.debug("Exception during poll: {}", e.getMessage(), e);
120             }
121         }
122     }
123
124     @Override
125     public void handleCommand(ChannelUID channelUID, Command command) {
126         String localHost = getHost();
127         if (localHost.isEmpty()) {
128             logger.warn("Failed to send command '{}' for device '{}': IP address missing", command,
129                     getThing().getUID());
130             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
131                     "@text/config-status.error.missing-ip");
132             return;
133         }
134         String wemoURL = getWemoURL(localHost, BASICACTION);
135         if (wemoURL == null) {
136             logger.debug("Failed to send command '{}' for device '{}': URL cannot be created", command,
137                     getThing().getUID());
138             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
139                     "@text/config-status.error.missing-url");
140             return;
141         }
142         if (command instanceof RefreshType) {
143             try {
144                 updateWemoState();
145             } catch (Exception e) {
146                 logger.debug("Exception during poll", e);
147             }
148         } else if (channelUID.getId().equals(CHANNEL_RELAY)) {
149             if (command instanceof OnOffType) {
150                 try {
151                     boolean binaryState = OnOffType.ON.equals(command) ? true : false;
152                     String soapHeader = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
153                     String content = createBinaryStateContent(binaryState);
154                     wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
155                     updateStatus(ThingStatus.ONLINE);
156                 } catch (Exception e) {
157                     logger.warn("Failed to send command '{}' for device '{}' ", command, getThing().getUID(), e);
158                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
159                 }
160             }
161         }
162     }
163
164     /**
165      * The {@link updateWemoState} polls the actual state of a WeMo Maker.
166      */
167     protected void updateWemoState() {
168         String localHost = getHost();
169         if (localHost.isEmpty()) {
170             logger.warn("Failed to get actual state for device '{}': IP address missing", getThing().getUID());
171             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
172                     "@text/config-status.error.missing-ip");
173             return;
174         }
175         String actionService = DEVICEACTION;
176         String wemoURL = getWemoURL(localHost, actionService);
177         if (wemoURL == null) {
178             logger.debug("Failed to get actual state for device '{}': URL cannot be created", getThing().getUID());
179             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
180                     "@text/config-status.error.missing-url");
181             return;
182         }
183         try {
184             String action = "GetAttributes";
185             String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\"";
186             String content = createStateRequestContent(action, actionService);
187             String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
188             try {
189                 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
190                 logger.trace("Escaped Maker response for device '{}' :", getThing().getUID());
191                 logger.trace("'{}'", stringParser);
192
193                 // Due to Belkins bad response formatting, we need to run this twice.
194                 stringParser = unescapeXml(stringParser);
195                 stringParser = unescapeXml(stringParser);
196                 logger.trace("Maker response '{}' for device '{}' received", stringParser, getThing().getUID());
197
198                 stringParser = "<data>" + stringParser + "</data>";
199
200                 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
201                 // see
202                 // https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
203                 dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
204                 dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
205                 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
206                 dbf.setXIncludeAware(false);
207                 dbf.setExpandEntityReferences(false);
208                 DocumentBuilder db = dbf.newDocumentBuilder();
209                 InputSource is = new InputSource();
210                 is.setCharacterStream(new StringReader(stringParser));
211
212                 Document doc = db.parse(is);
213                 NodeList nodes = doc.getElementsByTagName("attribute");
214
215                 // iterate the attributes
216                 for (int i = 0; i < nodes.getLength(); i++) {
217                     Element element = (Element) nodes.item(i);
218
219                     NodeList deviceIndex = element.getElementsByTagName("name");
220                     Element line = (Element) deviceIndex.item(0);
221                     String attributeName = getCharacterDataFromElement(line);
222                     logger.trace("attributeName: {}", attributeName);
223
224                     NodeList deviceID = element.getElementsByTagName("value");
225                     line = (Element) deviceID.item(0);
226                     String attributeValue = getCharacterDataFromElement(line);
227                     logger.trace("attributeValue: {}", attributeValue);
228
229                     switch (attributeName) {
230                         case "Switch":
231                             State relayState = "0".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
232                             logger.debug("New relayState '{}' for device '{}' received", relayState,
233                                     getThing().getUID());
234                             updateState(CHANNEL_RELAY, relayState);
235                             break;
236                         case "Sensor":
237                             State sensorState = "1".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
238                             logger.debug("New sensorState '{}' for device '{}' received", sensorState,
239                                     getThing().getUID());
240                             updateState(CHANNEL_SENSOR, sensorState);
241                             break;
242                     }
243                 }
244                 updateStatus(ThingStatus.ONLINE);
245             } catch (Exception e) {
246                 logger.warn("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e);
247             }
248         } catch (Exception e) {
249             logger.warn("Failed to get attributes for device '{}'", getThing().getUID(), e);
250             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
251         }
252     }
253 }