]> git.basschouten.com Git - openhab-addons.git/blob
61b3d413c285c530e2ed0976acde8bd6b3474786
[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.Set;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25
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;
46
47 /**
48  * The {@link WemoMakerHandler} is responsible for handling commands, which are
49  * sent to one of the channels and to update their states.
50  *
51  * @author Hans-Jörg Merk - Initial contribution
52  */
53 @NonNullByDefault
54 public class WemoMakerHandler extends WemoBaseThingHandler {
55
56     private final Logger logger = LoggerFactory.getLogger(WemoMakerHandler.class);
57
58     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MAKER);
59
60     private final Object jobLock = new Object();
61
62     private @Nullable ScheduledFuture<?> pollingJob;
63
64     public WemoMakerHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpcaller) {
65         super(thing, upnpIOService, wemoHttpcaller);
66
67         logger.debug("Creating a WemoMakerHandler for thing '{}'", getThing().getUID());
68     }
69
70     @Override
71     public void initialize() {
72         super.initialize();
73         Configuration configuration = getConfig();
74
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,
78                     TimeUnit.SECONDS);
79             updateStatus(ThingStatus.UNKNOWN);
80         } else {
81             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
82                     "@text/config-status.error.missing-udn");
83         }
84     }
85
86     @Override
87     public void dispose() {
88         logger.debug("WemoMakerHandler disposed.");
89
90         ScheduledFuture<?> job = this.pollingJob;
91         if (job != null && !job.isCancelled()) {
92             job.cancel(true);
93         }
94         this.pollingJob = null;
95         super.dispose();
96     }
97
98     private void poll() {
99         synchronized (jobLock) {
100             if (pollingJob == null) {
101                 return;
102             }
103             try {
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() + "\"]");
110                     return;
111                 }
112                 updateWemoState();
113             } catch (Exception e) {
114                 logger.debug("Exception during poll: {}", e.getMessage(), e);
115             }
116         }
117     }
118
119     @Override
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());
125             return;
126         }
127         if (command instanceof RefreshType) {
128             try {
129                 updateWemoState();
130             } catch (Exception e) {
131                 logger.debug("Exception during poll", e);
132             }
133         } else if (channelUID.getId().equals(CHANNEL_RELAY)) {
134             if (command instanceof OnOffType) {
135                 try {
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);
144                 }
145             }
146         }
147     }
148
149     /**
150      * The {@link updateWemoState} polls the actual state of a WeMo Maker.
151      */
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());
157             return;
158         }
159         try {
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);
164             try {
165                 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
166                 logger.trace("Escaped Maker response for device '{}' :", getThing().getUID());
167                 logger.trace("'{}'", stringParser);
168
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());
173
174                 stringParser = "<data>" + stringParser + "</data>";
175
176                 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
177                 // see
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));
187
188                 Document doc = db.parse(is);
189                 NodeList nodes = doc.getElementsByTagName("attribute");
190
191                 // iterate the attributes
192                 for (int i = 0; i < nodes.getLength(); i++) {
193                     Element element = (Element) nodes.item(i);
194
195                     NodeList deviceIndex = element.getElementsByTagName("name");
196                     Element line = (Element) deviceIndex.item(0);
197                     String attributeName = getCharacterDataFromElement(line);
198                     logger.trace("attributeName: {}", attributeName);
199
200                     NodeList deviceID = element.getElementsByTagName("value");
201                     line = (Element) deviceID.item(0);
202                     String attributeValue = getCharacterDataFromElement(line);
203                     logger.trace("attributeValue: {}", attributeValue);
204
205                     switch (attributeName) {
206                         case "Switch":
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);
211                             break;
212                         case "Sensor":
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);
217                             break;
218                     }
219                 }
220                 updateStatus(ThingStatus.ONLINE);
221             } catch (Exception e) {
222                 logger.warn("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e);
223             }
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());
227         }
228     }
229 }