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.regoheatpump.internal.protocol;
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;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * The {@link IpRegoConnection} is responsible for creating TCP/IP connections to clients.
27 * @author Boris Krivonog - Initial contribution
29 public class IpRegoConnection implements RegoConnection {
31 * Connection timeout in milliseconds
33 private static final int CONNECTION_TIMEOUT = 3000;
36 * Socket read timeout in milliseconds
38 private static final int SOCKET_READ_TIMEOUT = 2000;
40 private final Logger logger = LoggerFactory.getLogger(IpRegoConnection.class);
41 private final String address;
42 private final int port;
43 private Socket clientSocket;
45 public IpRegoConnection(String address, int port) {
46 this.address = address;
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);
58 clientSocket.connect(new InetSocketAddress(address, port), CONNECTION_TIMEOUT);
59 logger.debug("Connected to '{}', port = {}.", address, port);
63 public boolean isConnected() {
64 return clientSocket != null && clientSocket.isConnected();
70 if (clientSocket != null) {
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);
82 public OutputStream outputStream() throws IOException {
83 return clientSocket.getOutputStream();
87 public InputStream inputStream() throws IOException {
88 return clientSocket.getInputStream();