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;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.wemo.internal.http.WemoHttpCall;
29 import org.openhab.core.config.core.Configuration;
30 import org.openhab.core.io.transport.upnp.UpnpIOService;
31 import org.openhab.core.library.types.OnOffType;
32 import org.openhab.core.thing.ChannelUID;
33 import org.openhab.core.thing.Thing;
34 import org.openhab.core.thing.ThingStatus;
35 import org.openhab.core.thing.ThingStatusDetail;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.types.Command;
38 import org.openhab.core.types.RefreshType;
39 import org.openhab.core.types.State;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43 import org.w3c.dom.Element;
44 import org.w3c.dom.NodeList;
45 import org.xml.sax.InputSource;
48 * The {@link WemoMakerHandler} is responsible for handling commands, which are
49 * sent to one of the channels and to update their states.
51 * @author Hans-Jörg Merk - Initial contribution
54 public class WemoMakerHandler extends WemoBaseThingHandler {
56 private final Logger logger = LoggerFactory.getLogger(WemoMakerHandler.class);
58 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MAKER);
60 private final Object jobLock = new Object();
62 private @Nullable ScheduledFuture<?> pollingJob;
64 public WemoMakerHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpcaller) {
65 super(thing, upnpIOService, wemoHttpcaller);
67 logger.debug("Creating a WemoMakerHandler for thing '{}'", getThing().getUID());
71 public void initialize() {
73 Configuration configuration = getConfig();
75 if (configuration.get(UDN) != null) {
76 logger.debug("Initializing WemoMakerHandler for UDN '{}'", configuration.get(UDN));
77 pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, DEFAULT_REFRESH_INTERVAL_SECONDS,
79 updateStatus(ThingStatus.UNKNOWN);
81 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
82 "@text/config-status.error.missing-udn");
87 public void dispose() {
88 logger.debug("WemoMakerHandler disposed.");
90 ScheduledFuture<?> job = this.pollingJob;
91 if (job != null && !job.isCancelled()) {
94 this.pollingJob = null;
99 synchronized (jobLock) {
100 if (pollingJob == null) {
104 logger.debug("Polling job");
105 // Check if the Wemo device is set in the UPnP service registry
106 if (!isUpnpDeviceRegistered()) {
107 logger.debug("UPnP device {} not yet registered", getUDN());
108 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
109 "@text/config-status.pending.device-not-registered [\"" + getUDN() + "\"]");
113 } catch (Exception e) {
114 logger.debug("Exception during poll: {}", e.getMessage(), e);
120 public void handleCommand(ChannelUID channelUID, Command command) {
121 String wemoURL = getWemoURL(BASICACTION);
122 if (wemoURL == null) {
123 logger.debug("Failed to send command '{}' for device '{}': URL cannot be created", command,
124 getThing().getUID());
127 if (command instanceof RefreshType) {
130 } catch (Exception e) {
131 logger.debug("Exception during poll", e);
133 } else if (channelUID.getId().equals(CHANNEL_RELAY)) {
134 if (command instanceof OnOffType) {
136 boolean binaryState = OnOffType.ON.equals(command) ? true : false;
137 String soapHeader = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
138 String content = createBinaryStateContent(binaryState);
139 wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
140 updateStatus(ThingStatus.ONLINE);
141 } catch (Exception e) {
142 logger.warn("Failed to send command '{}' for device '{}' ", command, getThing().getUID(), e);
143 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
150 * The {@link updateWemoState} polls the actual state of a WeMo Maker.
152 protected void updateWemoState() {
153 String actionService = DEVICEACTION;
154 String wemoURL = getWemoURL(actionService);
155 if (wemoURL == null) {
156 logger.debug("Failed to get actual state for device '{}': URL cannot be created", getThing().getUID());
160 String action = "GetAttributes";
161 String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\"";
162 String content = createStateRequestContent(action, actionService);
163 String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
165 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
166 logger.trace("Escaped Maker response for device '{}' :", getThing().getUID());
167 logger.trace("'{}'", stringParser);
169 // Due to Belkins bad response formatting, we need to run this twice.
170 stringParser = unescapeXml(stringParser);
171 stringParser = unescapeXml(stringParser);
172 logger.trace("Maker response '{}' for device '{}' received", stringParser, getThing().getUID());
174 stringParser = "<data>" + stringParser + "</data>";
176 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
178 // https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
179 dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
180 dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
181 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
182 dbf.setXIncludeAware(false);
183 dbf.setExpandEntityReferences(false);
184 DocumentBuilder db = dbf.newDocumentBuilder();
185 InputSource is = new InputSource();
186 is.setCharacterStream(new StringReader(stringParser));
188 Document doc = db.parse(is);
189 NodeList nodes = doc.getElementsByTagName("attribute");
191 // iterate the attributes
192 for (int i = 0; i < nodes.getLength(); i++) {
193 Element element = (Element) nodes.item(i);
195 NodeList deviceIndex = element.getElementsByTagName("name");
196 Element line = (Element) deviceIndex.item(0);
197 String attributeName = getCharacterDataFromElement(line);
198 logger.trace("attributeName: {}", attributeName);
200 NodeList deviceID = element.getElementsByTagName("value");
201 line = (Element) deviceID.item(0);
202 String attributeValue = getCharacterDataFromElement(line);
203 logger.trace("attributeValue: {}", attributeValue);
205 switch (attributeName) {
207 State relayState = "0".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
208 logger.debug("New relayState '{}' for device '{}' received", relayState,
209 getThing().getUID());
210 updateState(CHANNEL_RELAY, relayState);
213 State sensorState = "1".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
214 logger.debug("New sensorState '{}' for device '{}' received", sensorState,
215 getThing().getUID());
216 updateState(CHANNEL_SENSOR, sensorState);
220 updateStatus(ThingStatus.ONLINE);
221 } catch (Exception e) {
222 logger.warn("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e);
224 } catch (Exception e) {
225 logger.warn("Failed to get attributes for device '{}'", getThing().getUID(), e);
226 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());