]> git.basschouten.com Git - openhab-addons.git/blob
04345c37446aba37d53fbba4eacbdca04f23cea2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.io.imperihome.internal.handler;
14
15 import java.io.UnsupportedEncodingException;
16 import java.net.URLDecoder;
17 import java.util.regex.Matcher;
18
19 import javax.servlet.http.HttpServletRequest;
20
21 import org.openhab.io.imperihome.internal.model.device.AbstractDevice;
22 import org.openhab.io.imperihome.internal.processor.DeviceRegistry;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Device action request handler.
28  *
29  * @author Pepijn de Geus - Initial contribution
30  */
31 public class DeviceActionHandler {
32
33     private static final String CHARSET = "UTF-8";
34
35     private final Logger logger = LoggerFactory.getLogger(DeviceActionHandler.class);
36
37     private final DeviceRegistry deviceRegistry;
38
39     public DeviceActionHandler(DeviceRegistry deviceRegistry) {
40         this.deviceRegistry = deviceRegistry;
41     }
42
43     public void handle(HttpServletRequest req, Matcher urlMatcher) {
44         String deviceId, action, value;
45         try {
46             deviceId = URLDecoder.decode(urlMatcher.group(1), CHARSET);
47             action = URLDecoder.decode(urlMatcher.group(2), CHARSET);
48
49             if (urlMatcher.group(3) == null) {
50                 value = null;
51             } else {
52                 value = URLDecoder.decode(urlMatcher.group(3), CHARSET);
53             }
54         } catch (UnsupportedEncodingException e) {
55             throw new RuntimeException("Could not decode request params", e);
56         }
57
58         logger.debug("Action request for device {}: [{}] [{}]", deviceId, action, value);
59
60         AbstractDevice device = deviceRegistry.getDevice(deviceId);
61         if (device == null) {
62             logger.warn("Received action request for unknown device: {}", urlMatcher.group(0));
63         } else {
64             device.performAction(action, value);
65         }
66     }
67 }