]> git.basschouten.com Git - openhab-addons.git/blob
a2e620e827173bd37d36578562f3450cc4db5fc5
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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             pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, DEFAULT_REFRESH_INTERVAL_SECONDS,
79                     TimeUnit.SECONDS);
80             updateStatus(ThingStatus.UNKNOWN);
81         } else {
82             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
83                     "@text/config-status.error.missing-udn");
84         }
85     }
86
87     @Override
88     public void dispose() {
89         logger.debug("WemoMakerHandler disposed.");
90
91         ScheduledFuture<?> job = this.pollingJob;
92         if (job != null && !job.isCancelled()) {
93             job.cancel(true);
94         }
95         this.pollingJob = null;
96         super.dispose();
97     }
98
99     private void poll() {
100         synchronized (jobLock) {
101             if (pollingJob == null) {
102                 return;
103             }
104             try {
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() + "\"]");
111                     return;
112                 }
113                 updateWemoState();
114             } catch (Exception e) {
115                 logger.debug("Exception during poll: {}", e.getMessage(), e);
116             }
117         }
118     }
119
120     @Override
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());
126             return;
127         }
128         if (command instanceof RefreshType) {
129             try {
130                 updateWemoState();
131             } catch (Exception e) {
132                 logger.debug("Exception during poll", e);
133             }
134         } else if (channelUID.getId().equals(CHANNEL_RELAY)) {
135             if (command instanceof OnOffType) {
136                 try {
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);
145                 }
146             }
147         }
148     }
149
150     /**
151      * The {@link updateWemoState} polls the actual state of a WeMo Maker.
152      */
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());
158             return;
159         }
160         try {
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);
165             try {
166                 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
167                 logger.trace("Escaped Maker response for device '{}' :", getThing().getUID());
168                 logger.trace("'{}'", stringParser);
169
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());
174
175                 stringParser = "<data>" + stringParser + "</data>";
176
177                 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
178                 // see
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));
188
189                 Document doc = db.parse(is);
190                 NodeList nodes = doc.getElementsByTagName("attribute");
191
192                 // iterate the attributes
193                 for (int i = 0; i < nodes.getLength(); i++) {
194                     Element element = (Element) nodes.item(i);
195
196                     NodeList deviceIndex = element.getElementsByTagName("name");
197                     Element line = (Element) deviceIndex.item(0);
198                     String attributeName = getCharacterDataFromElement(line);
199                     logger.trace("attributeName: {}", attributeName);
200
201                     NodeList deviceID = element.getElementsByTagName("value");
202                     line = (Element) deviceID.item(0);
203                     String attributeValue = getCharacterDataFromElement(line);
204                     logger.trace("attributeValue: {}", attributeValue);
205
206                     switch (attributeName) {
207                         case "Switch":
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);
212                             break;
213                         case "Sensor":
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);
218                             break;
219                     }
220                 }
221                 updateStatus(ThingStatus.ONLINE);
222             } catch (Exception e) {
223                 logger.warn("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e);
224             }
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());
228         }
229     }
230 }