2 * Copyright (c) 2010-2022 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.io.StringReader;
19 import java.util.Collections;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
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;
49 * The {@link WemoMakerHandler} is responsible for handling commands, which are
50 * sent to one of the channels and to update their states.
52 * @author Hans-Jörg Merk - Initial contribution
55 public class WemoMakerHandler extends WemoBaseThingHandler {
57 private final Logger logger = LoggerFactory.getLogger(WemoMakerHandler.class);
59 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MAKER);
61 private final Object jobLock = new Object();
63 private @Nullable ScheduledFuture<?> pollingJob;
65 public WemoMakerHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpcaller) {
66 super(thing, upnpIOService, wemoHttpcaller);
68 logger.debug("Creating a WemoMakerHandler for thing '{}'", getThing().getUID());
72 public void initialize() {
74 Configuration configuration = getConfig();
76 if (configuration.get(UDN) != null) {
77 logger.debug("Initializing WemoMakerHandler for UDN '{}'", configuration.get(UDN));
79 pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, DEFAULT_REFRESH_INTERVAL_SECONDS,
81 updateStatus(ThingStatus.ONLINE);
83 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
84 "@text/config-status.error.missing-udn");
85 logger.debug("Cannot initalize WemoMakerHandler. UDN not set.");
90 public void dispose() {
91 logger.debug("WemoMakerHandler disposed.");
93 ScheduledFuture<?> job = this.pollingJob;
94 if (job != null && !job.isCancelled()) {
97 this.pollingJob = null;
101 private void poll() {
102 synchronized (jobLock) {
103 if (pollingJob == null) {
107 logger.debug("Polling job");
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() + "\"]");
118 } catch (Exception e) {
119 logger.debug("Exception during poll: {}", e.getMessage(), e);
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");
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");
142 if (command instanceof RefreshType) {
145 } catch (Exception e) {
146 logger.debug("Exception during poll", e);
148 } else if (channelUID.getId().equals(CHANNEL_RELAY)) {
149 if (command instanceof OnOffType) {
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);
165 * The {@link updateWemoState} polls the actual state of a WeMo Maker.
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");
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");
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);
189 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
190 logger.trace("Escaped Maker response for device '{}' :", getThing().getUID());
191 logger.trace("'{}'", stringParser);
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());
198 stringParser = "<data>" + stringParser + "</data>";
200 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
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));
212 Document doc = db.parse(is);
213 NodeList nodes = doc.getElementsByTagName("attribute");
215 // iterate the attributes
216 for (int i = 0; i < nodes.getLength(); i++) {
217 Element element = (Element) nodes.item(i);
219 NodeList deviceIndex = element.getElementsByTagName("name");
220 Element line = (Element) deviceIndex.item(0);
221 String attributeName = getCharacterDataFromElement(line);
222 logger.trace("attributeName: {}", attributeName);
224 NodeList deviceID = element.getElementsByTagName("value");
225 line = (Element) deviceID.item(0);
226 String attributeValue = getCharacterDataFromElement(line);
227 logger.trace("attributeValue: {}", attributeValue);
229 switch (attributeName) {
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);
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);
244 updateStatus(ThingStatus.ONLINE);
245 } catch (Exception e) {
246 logger.warn("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e);
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());