]> git.basschouten.com Git - openhab-addons.git/blob
1a31d4db98a8c4def9e1e834feea8e5503130a12
[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.binding.regoheatpump.internal.protocol;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18 import java.net.InetSocketAddress;
19 import java.net.Socket;
20
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * The {@link IpRegoConnection} is responsible for creating TCP/IP connections to clients.
26  *
27  * @author Boris Krivonog - Initial contribution
28  */
29 public class IpRegoConnection implements RegoConnection {
30     /**
31      * Connection timeout in milliseconds
32      **/
33     private static final int CONNECTION_TIMEOUT = 3000;
34
35     /**
36      * Socket read timeout in milliseconds
37      **/
38     private static final int SOCKET_READ_TIMEOUT = 2000;
39
40     private final Logger logger = LoggerFactory.getLogger(IpRegoConnection.class);
41     private final String address;
42     private final int port;
43     private Socket clientSocket;
44
45     public IpRegoConnection(String address, int port) {
46         this.address = address;
47         this.port = port;
48     }
49
50     @Override
51     public void connect() throws IOException {
52         logger.debug("Connecting to '{}', port = {}.", address, port);
53         if (clientSocket == null) {
54             clientSocket = new Socket();
55             clientSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
56             clientSocket.setKeepAlive(true);
57         }
58         clientSocket.connect(new InetSocketAddress(address, port), CONNECTION_TIMEOUT);
59         logger.debug("Connected to '{}', port = {}.", address, port);
60     }
61
62     @Override
63     public boolean isConnected() {
64         return clientSocket != null && clientSocket.isConnected();
65     }
66
67     @Override
68     public void close() {
69         try {
70             if (clientSocket != null) {
71                 clientSocket.close();
72             }
73         } catch (IOException e) {
74             // There is really not much we can do here, ignore the error and continue execution.
75             logger.warn("Closing socket failed", e);
76         }
77
78         clientSocket = null;
79     }
80
81     @Override
82     public OutputStream outputStream() throws IOException {
83         return clientSocket.getOutputStream();
84     }
85
86     @Override
87     public InputStream inputStream() throws IOException {
88         return clientSocket.getInputStream();
89     }
90 }