]> git.basschouten.com Git - openhab-addons.git/blob
f5ed05ea508fcd03d0e6153a8289458a2a0e53f6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.neohub.internal;
14
15 import static java.nio.charset.StandardCharsets.US_ASCII;
16
17 import java.io.IOException;
18 import java.io.InputStreamReader;
19 import java.io.OutputStreamWriter;
20 import java.net.InetSocketAddress;
21 import java.net.Socket;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * NeoHubConnector handles the ASCII based communication via TCP between openHAB
29  * and NeoHub
30  *
31  * @author Sebastian Prehn - Initial contribution
32  * @author Andrew Fiddian-Green - Refactoring for openHAB v2.x
33  *
34  */
35 @NonNullByDefault
36 public class NeoHubSocket {
37
38     private final Logger logger = LoggerFactory.getLogger(NeoHubSocket.class);
39
40     /**
41      * Name of host or IP to connect to.
42      */
43     private final String hostname;
44
45     /**
46      * The port to connect to
47      */
48     private final int port;
49
50     /**
51      * The socket connect resp. read timeout value
52      */
53     private final int timeout;
54
55     public NeoHubSocket(final String hostname, final int portNumber, final int timeoutSeconds) {
56         this.hostname = hostname;
57         this.port = portNumber;
58         this.timeout = timeoutSeconds * 1000;
59     }
60
61     /**
62      * sends the message over the network to the NeoHub and returns its response
63      *
64      * @param requestJson the message to be sent to the NeoHub
65      * @return responseJson received from NeoHub
66      * @throws NeoHubException, IOException
67      * 
68      */
69     public String sendMessage(final String requestJson) throws IOException, NeoHubException {
70         IOException caughtException = null;
71         StringBuilder builder = new StringBuilder();
72
73         try (Socket socket = new Socket()) {
74             socket.connect(new InetSocketAddress(hostname, port), timeout);
75             socket.setSoTimeout(timeout);
76
77             try (InputStreamReader reader = new InputStreamReader(socket.getInputStream(), US_ASCII);
78                     OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), US_ASCII)) {
79                 if (logger.isDebugEnabled()) {
80                     logger.debug("sending {} characters..", requestJson.length());
81                     logger.debug(">> {}", requestJson);
82                 }
83
84                 writer.write(requestJson);
85                 writer.write(0); // NULL terminate the command string
86                 writer.flush();
87
88                 if (logger.isTraceEnabled()) {
89                     logger.trace("sent {} characters..", requestJson.length());
90                 }
91
92                 int inChar;
93                 // NULL termination, end of stream (-1), or newline
94                 while (((inChar = reader.read()) > 0) && (inChar != '\n')) {
95                     builder.append((char) inChar);
96                 }
97             }
98         } catch (IOException e) {
99             // catch IOExceptions here, and save them to be re-thrown later
100             caughtException = e;
101         }
102
103         String responseJson = builder.toString();
104
105         if (logger.isTraceEnabled()) {
106             logger.trace("received {} characters..", responseJson.length());
107             logger.trace("<< {}", responseJson);
108         } else
109
110         if (logger.isDebugEnabled()) {
111             logger.debug("received {} characters (set log level to TRACE to see full string)..", responseJson.length());
112             logger.debug("<< {} ...", responseJson.substring(0, Math.min(responseJson.length(), 30)));
113         }
114
115         // if any type of Exception was caught above, re-throw it again to the caller
116         if (caughtException != null) {
117             throw caughtException;
118         }
119
120         if (responseJson.isEmpty()) {
121             throw new NeoHubException("empty response string");
122         }
123
124         return responseJson;
125     }
126 }