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.time.Instant;
20 import java.time.ZonedDateTime;
21 import java.util.Collections;
23 import java.util.TimeZone;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
27 import javax.xml.parsers.DocumentBuilder;
28 import javax.xml.parsers.DocumentBuilderFactory;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.wemo.internal.http.WemoHttpCall;
33 import org.openhab.core.config.core.Configuration;
34 import org.openhab.core.io.transport.upnp.UpnpIOService;
35 import org.openhab.core.library.types.DateTimeType;
36 import org.openhab.core.library.types.DecimalType;
37 import org.openhab.core.library.types.OnOffType;
38 import org.openhab.core.library.types.StringType;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.thing.ThingTypeUID;
44 import org.openhab.core.types.Command;
45 import org.openhab.core.types.RefreshType;
46 import org.openhab.core.types.State;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51 import org.w3c.dom.NodeList;
52 import org.xml.sax.InputSource;
55 * The {@link WemoCoffeeHandler} is responsible for handling commands, which are
56 * sent to one of the channels and to update their states.
58 * @author Hans-Jörg Merk - Initial contribution
59 * @author Erdoan Hadzhiyusein - Adapted the class to work with the new DateTimeType
62 public class WemoCoffeeHandler extends WemoBaseThingHandler {
64 private final Logger logger = LoggerFactory.getLogger(WemoCoffeeHandler.class);
66 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_COFFEE);
68 private final Object jobLock = new Object();
70 private @Nullable ScheduledFuture<?> pollingJob;
72 public WemoCoffeeHandler(Thing thing, UpnpIOService upnpIOService, WemoHttpCall wemoHttpCaller) {
73 super(thing, upnpIOService, wemoHttpCaller);
75 logger.debug("Creating a WemoCoffeeHandler for thing '{}'", getThing().getUID());
79 public void initialize() {
81 Configuration configuration = getConfig();
83 if (configuration.get(UDN) != null) {
84 logger.debug("Initializing WemoCoffeeHandler for UDN '{}'", configuration.get(UDN));
85 addSubscription(DEVICEEVENT);
86 pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, DEFAULT_REFRESH_INTERVAL_SECONDS,
88 updateStatus(ThingStatus.ONLINE);
90 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
91 "@text/config-status.error.missing-udn");
92 logger.debug("Cannot initalize WemoCoffeeHandler. UDN not set.");
97 public void dispose() {
98 logger.debug("WemoCoffeeHandler disposed.");
99 ScheduledFuture<?> job = this.pollingJob;
100 if (job != null && !job.isCancelled()) {
103 this.pollingJob = null;
107 private void poll() {
108 synchronized (jobLock) {
109 if (pollingJob == null) {
113 logger.debug("Polling job");
115 // Check if the Wemo device is set in the UPnP service registry
116 // If not, set the thing state to ONLINE/CONFIG-PENDING and wait for the next poll
117 if (!isUpnpDeviceRegistered()) {
118 logger.debug("UPnP device {} not yet registered", getUDN());
119 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
120 "@text/config-status.pending.device-not-registered [\"" + getUDN() + "\"]");
124 } catch (Exception e) {
125 logger.debug("Exception during poll: {}", e.getMessage(), e);
131 public void handleCommand(ChannelUID channelUID, Command command) {
132 String wemoURL = getWemoURL(BASICACTION);
133 if (wemoURL == null) {
134 logger.debug("Failed to send command '{}' for device '{}': URL cannot be created", command,
135 getThing().getUID());
138 if (command instanceof RefreshType) {
141 } catch (Exception e) {
142 logger.debug("Exception during poll", e);
144 } else if (channelUID.getId().equals(CHANNEL_STATE)) {
145 if (command instanceof OnOffType) {
146 if (command.equals(OnOffType.ON)) {
148 String soapHeader = "\"urn:Belkin:service:deviceevent:1#SetAttributes\"";
150 String content = "<?xml version=\"1.0\"?>"
151 + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
152 + "<s:Body>" + "<u:SetAttributes xmlns:u=\"urn:Belkin:service:deviceevent:1\">"
153 + "<attributeList><attribute><name>Brewed</name><value>NULL</value></attribute>"
154 + "<attribute><name>LastCleaned</name><value>NULL</value></attribute><attribute>"
155 + "<name>ModeTime</name><value>NULL</value></attribute><attribute><name>Brewing</name>"
156 + "<value>NULL</value></attribute><attribute><name>TimeRemaining</name><value>NULL</value>"
157 + "</attribute><attribute><name>WaterLevelReached</name><value>NULL</value></attribute><"
158 + "attribute><name>Mode</name><value>4</value></attribute><attribute><name>CleanAdvise</name>"
159 + "<value>NULL</value></attribute><attribute><name>FilterAdvise</name><value>NULL</value></attribute>"
160 + "<attribute><name>Cleaning</name><value>NULL</value></attribute></attributeList>"
161 + "</u:SetAttributes>" + "</s:Body>" + "</s:Envelope>";
163 wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
164 updateState(CHANNEL_STATE, OnOffType.ON);
165 State newMode = new StringType("Brewing");
166 updateState(CHANNEL_COFFEEMODE, newMode);
167 updateStatus(ThingStatus.ONLINE);
168 } catch (Exception e) {
169 logger.warn("Failed to send command '{}' for device '{}': {}", command, getThing().getUID(),
171 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
174 // if command.equals(OnOffType.OFF) we do nothing because WeMo Coffee Maker cannot be switched
181 public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
182 // We can subscribe to GENA events, but there is no usefull response right now.
186 * The {@link updateWemoState} polls the actual state of a WeMo CoffeeMaker.
188 protected void updateWemoState() {
189 String actionService = DEVICEACTION;
190 String wemoURL = getWemoURL(actionService);
191 if (wemoURL == null) {
192 logger.debug("Failed to get actual state for device '{}': URL cannot be created", getThing().getUID());
196 String action = "GetAttributes";
197 String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\"";
198 String content = createStateRequestContent(action, actionService);
199 String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
201 String stringParser = substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>");
203 // Due to Belkins bad response formatting, we need to run this twice.
204 stringParser = unescapeXml(stringParser);
205 stringParser = unescapeXml(stringParser);
207 logger.trace("CoffeeMaker response '{}' for device '{}' received", stringParser, getThing().getUID());
209 stringParser = "<data>" + stringParser + "</data>";
211 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
213 // https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
214 dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
215 dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
216 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
217 dbf.setXIncludeAware(false);
218 dbf.setExpandEntityReferences(false);
219 DocumentBuilder db = dbf.newDocumentBuilder();
220 InputSource is = new InputSource();
221 is.setCharacterStream(new StringReader(stringParser));
223 Document doc = db.parse(is);
224 NodeList nodes = doc.getElementsByTagName("attribute");
226 // iterate the attributes
227 for (int i = 0; i < nodes.getLength(); i++) {
228 Element element = (Element) nodes.item(i);
230 NodeList deviceIndex = element.getElementsByTagName("name");
231 Element line = (Element) deviceIndex.item(0);
232 String attributeName = getCharacterDataFromElement(line);
233 logger.trace("attributeName: {}", attributeName);
235 NodeList deviceID = element.getElementsByTagName("value");
236 line = (Element) deviceID.item(0);
237 String attributeValue = getCharacterDataFromElement(line);
238 logger.trace("attributeValue: {}", attributeValue);
240 switch (attributeName) {
242 State newMode = new StringType("Brewing");
243 State newAttributeValue;
245 switch (attributeValue) {
247 updateState(CHANNEL_STATE, OnOffType.ON);
248 newMode = new StringType("Refill");
249 updateState(CHANNEL_COFFEEMODE, newMode);
252 updateState(CHANNEL_STATE, OnOffType.OFF);
253 newMode = new StringType("PlaceCarafe");
254 updateState(CHANNEL_COFFEEMODE, newMode);
257 updateState(CHANNEL_STATE, OnOffType.OFF);
258 newMode = new StringType("RefillWater");
259 updateState(CHANNEL_COFFEEMODE, newMode);
262 updateState(CHANNEL_STATE, OnOffType.OFF);
263 newMode = new StringType("Ready");
264 updateState(CHANNEL_COFFEEMODE, newMode);
267 updateState(CHANNEL_STATE, OnOffType.ON);
268 newMode = new StringType("Brewing");
269 updateState(CHANNEL_COFFEEMODE, newMode);
272 updateState(CHANNEL_STATE, OnOffType.OFF);
273 newMode = new StringType("Brewed");
274 updateState(CHANNEL_COFFEEMODE, newMode);
277 updateState(CHANNEL_STATE, OnOffType.OFF);
278 newMode = new StringType("CleaningBrewing");
279 updateState(CHANNEL_COFFEEMODE, newMode);
282 updateState(CHANNEL_STATE, OnOffType.OFF);
283 newMode = new StringType("CleaningSoaking");
284 updateState(CHANNEL_COFFEEMODE, newMode);
287 updateState(CHANNEL_STATE, OnOffType.OFF);
288 newMode = new StringType("BrewFailCarafeRemoved");
289 updateState(CHANNEL_COFFEEMODE, newMode);
294 newAttributeValue = new DecimalType(attributeValue);
295 updateState(CHANNEL_MODETIME, newAttributeValue);
297 case "TimeRemaining":
298 newAttributeValue = new DecimalType(attributeValue);
299 updateState(CHANNEL_TIMEREMAINING, newAttributeValue);
301 case "WaterLevelReached":
302 newAttributeValue = new DecimalType(attributeValue);
303 updateState(CHANNEL_WATERLEVELREACHED, newAttributeValue);
306 newAttributeValue = "0".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
307 updateState(CHANNEL_CLEANADVISE, newAttributeValue);
310 newAttributeValue = "0".equals(attributeValue) ? OnOffType.OFF : OnOffType.ON;
311 updateState(CHANNEL_FILTERADVISE, newAttributeValue);
314 newAttributeValue = getDateTimeState(attributeValue);
315 if (newAttributeValue != null) {
316 updateState(CHANNEL_BREWED, newAttributeValue);
320 newAttributeValue = getDateTimeState(attributeValue);
321 if (newAttributeValue != null) {
322 updateState(CHANNEL_LASTCLEANED, newAttributeValue);
327 updateStatus(ThingStatus.ONLINE);
328 } catch (Exception e) {
329 logger.warn("Failed to parse attributeList for WeMo CoffeMaker '{}'", this.getThing().getUID(), e);
331 } catch (Exception e) {
332 logger.warn("Failed to get attributes for device '{}'", getThing().getUID(), e);
333 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
337 public @Nullable State getDateTimeState(String attributeValue) {
340 value = Long.parseLong(attributeValue);
341 } catch (NumberFormatException e) {
342 logger.warn("Unable to parse attributeValue '{}' for device '{}'; expected long", attributeValue,
343 getThing().getUID());
346 ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochSecond(value), TimeZone.getDefault().toZoneId());
347 State dateTimeState = new DateTimeType(zoned);
348 logger.trace("New attribute brewed '{}' received", dateTimeState);
349 return dateTimeState;