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.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));
78 pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, DEFAULT_REFRESH_INTERVAL_SECONDS,
80 updateStatus(ThingStatus.UNKNOWN);
82 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
83 "@text/config-status.error.missing-udn");
88 public void dispose() {
89 logger.debug("WemoMakerHandler disposed.");
91 ScheduledFuture<?> job = this.pollingJob;
92 if (job != null && !job.isCancelled()) {
95 this.pollingJob = null;
100 synchronized (jobLock) {
101 if (pollingJob == null) {
105 logger.debug("Polling job");
106 // Check if the Wemo device is set in the UPnP service registry
107 if (!isUpnpDeviceRegistered()) {
108 logger.debug("UPnP device {} not yet registered", getUDN());
109 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
110 "@text/config-status.pending.device-not-registered [\"" + getUDN() + "\"]");
114 } catch (Exception e) {
115 logger.debug("Exception during poll: {}", e.getMessage(), e);
121 public void handleCommand(ChannelUID channelUID, Command command) {
122 String wemoURL = getWemoURL(BASICACTION);
123 if (wemoURL == null) {
124 logger.debug("Failed to send command '{}' for device '{}': URL cannot be created", command,
125 getThing().getUID());
128 if (command instanceof RefreshType) {
131 } catch (Exception e) {
132 logger.debug("Exception during poll", e);
134 } else if (channelUID.getId().equals(CHANNEL_RELAY)) {
135 if (command instanceof OnOffType) {
137 boolean binaryState = OnOffType.ON.equals(command) ? true : false;
138 String soapHeader = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
139 String content = createBinaryStateContent(binaryState);
140 wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
141 updateStatus(ThingStatus.ONLINE);
142 } catch (Exception e) {
143 logger.warn("Failed to send command '{}' for device '{}' ", command, getThing().getUID(), e);
144 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
151 * The {@link updateWemoState} polls the actual state of a WeMo Maker.
153 protected void updateWemoState() {
154 String actionService = DEVICEACTION;
155 String wemoURL = getWemoURL(actionService);
156 if (wemoURL == null) {
157 logger.debug("Failed to get actual state for device '{}': URL cannot be created", getThing().getUID());
161 String action = "GetAttributes";
162 String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\"";
163 String content = createStateRequestContent(action, actionService);
164 String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
166 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
167 logger.trace("Escaped Maker response for device '{}' :", getThing().getUID());
168 logger.trace("'{}'", stringParser);
170 // Due to Belkins bad response formatting, we need to run this twice.
171 stringParser = unescapeXml(stringParser);
172 stringParser = unescapeXml(stringParser);
173 logger.trace("Maker response '{}' for device '{}' received", stringParser, getThing().getUID());
175 stringParser = "<data>" + stringParser + "</data>";
177 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
179 // https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
180 dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
181 dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
182 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
183 dbf.setXIncludeAware(false);
184 dbf.setExpandEntityReferences(false);
185 DocumentBuilder db = dbf.newDocumentBuilder();
186 InputSource is = new InputSource();
187 is.setCharacterStream(new StringReader(stringParser));
189 Document doc = db.parse(is);
190 NodeList nodes = doc.getElementsByTagName("attribute");
192 // iterate the attributes
193 for (int i = 0; i < nodes.getLength(); i++) {
194 Element element = (Element) nodes.item(i);
196 NodeList deviceIndex = element.getElementsByTagName("name");
197 Element line = (Element) deviceIndex.item(0);
198 String attributeName = getCharacterDataFromElement(line);
199 logger.trace("attributeName: {}", attributeName);
201 NodeList deviceID = element.getElementsByTagName("value");
202 line = (Element) deviceID.item(0);
203 String attributeValue = getCharacterDataFromElement(line);
204 logger.trace("attributeValue: {}", attributeValue);
206 switch (attributeName) {
208 State relayState = "0".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
209 logger.debug("New relayState '{}' for device '{}' received", relayState,
210 getThing().getUID());
211 updateState(CHANNEL_RELAY, relayState);
214 State sensorState = "1".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
215 logger.debug("New sensorState '{}' for device '{}' received", sensorState,
216 getThing().getUID());
217 updateState(CHANNEL_SENSOR, sensorState);
221 updateStatus(ThingStatus.ONLINE);
222 } catch (Exception e) {
223 logger.warn("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e);
225 } catch (Exception e) {
226 logger.warn("Failed to get attributes for device '{}'", getThing().getUID(), e);
227 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());