2 * Copyright (c) 2010-2023 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.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * The {@link IpRegoConnection} is responsible for creating TCP/IP connections to clients.
29 * @author Boris Krivonog - Initial contribution
32 public class IpRegoConnection implements RegoConnection {
34 * Connection timeout in milliseconds
36 private static final int CONNECTION_TIMEOUT = 3000;
39 * Socket read timeout in milliseconds
41 private static final int SOCKET_READ_TIMEOUT = 2000;
43 private final Logger logger = LoggerFactory.getLogger(IpRegoConnection.class);
44 private final String address;
45 private final int port;
46 private @Nullable Socket clientSocket;
48 public IpRegoConnection(String address, int port) {
49 this.address = address;
54 public void connect() throws IOException {
55 logger.debug("Connecting to '{}', port = {}.", address, port);
56 Socket clientSocket = this.clientSocket;
57 if (clientSocket == null) {
58 clientSocket = new Socket();
59 clientSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
60 clientSocket.setKeepAlive(true);
61 this.clientSocket = clientSocket;
63 clientSocket.connect(new InetSocketAddress(address, port), CONNECTION_TIMEOUT);
64 logger.debug("Connected to '{}', port = {}.", address, port);
68 public boolean isConnected() {
69 Socket clientSocket = this.clientSocket;
70 return clientSocket != null && clientSocket.isConnected();
76 Socket clientSocket = this.clientSocket;
77 this.clientSocket = null;
78 if (clientSocket != null) {
81 } catch (IOException e) {
82 // There is really not much we can do here, ignore the error and continue execution.
83 logger.warn("Closing socket failed", e);
88 public OutputStream outputStream() throws IOException {
89 return getClientSocket().getOutputStream();
93 public InputStream inputStream() throws IOException {
94 return getClientSocket().getInputStream();
97 private Socket getClientSocket() throws IOException {
98 Socket clientSocket = this.clientSocket;
99 if (clientSocket == null) {
100 throw new IOException("Socket closed");