2 * Copyright (c) 2010-2024 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.insteon.internal.driver;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18 import java.net.Socket;
19 import java.net.UnknownHostException;
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 * Implements IOStream for the older hubs (pre 2014).
28 * Also works for serial ports exposed via tcp, eg. ser2net
30 * @author Bernd Pfrommer - Initial contribution
31 * @author Rob Nielsen - Port to openHAB 2 insteon binding
35 public class TcpIOStream extends IOStream {
36 private final Logger logger = LoggerFactory.getLogger(TcpIOStream.class);
38 private @Nullable String host = null;
39 private int port = -1;
40 private @Nullable Socket socket = null;
45 * @param host host name of hub device
46 * @param port port to connect to
48 public TcpIOStream(String host, int port) {
54 public boolean open() {
55 if (host == null || port < 0) {
56 logger.warn("tcp connection to hub not properly configured!");
60 socket = new Socket(host, port);
62 } catch (UnknownHostException e) {
63 logger.warn("unknown host name: {}", host);
65 } catch (IOException e) {
66 logger.warn("cannot open connection to {} port {}: {}", host, port, e.getMessage());
72 private void open(@Nullable Socket socket) throws IOException {
74 in = socket.getInputStream();
75 out = socket.getOutputStream();
81 InputStream in = this.in;
85 } catch (IOException e) {
86 logger.warn("failed to close input stream", e);
91 OutputStream out = this.out;
95 } catch (IOException e) {
96 logger.warn("failed to close output stream", e);
101 Socket socket = this.socket;
102 if (socket != null) {
105 } catch (IOException e) {
106 logger.warn("failed to close the socket", e);