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.rfxcom.internal.connector;
15 import java.io.IOException;
16 import java.io.OutputStream;
17 import java.net.Socket;
18 import java.net.SocketTimeoutException;
20 import org.openhab.binding.rfxcom.internal.config.RFXComBridgeConfiguration;
21 import org.openhab.core.util.HexUtils;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * RFXCOM connector for TCP/IP communication.
28 * @author Pauli Anttila - Initial contribution
29 * @author Ivan F. Martinez, James Hewitt-Thomas - Implementation
31 public class RFXComTcpConnector extends RFXComBaseConnector {
32 private final Logger logger = LoggerFactory.getLogger(RFXComTcpConnector.class);
34 private OutputStream out;
35 private Socket socket;
37 private final String readerThreadName;
38 private Thread readerThread;
40 public RFXComTcpConnector(String readerThreadName) {
42 this.readerThreadName = readerThreadName;
46 public void connect(RFXComBridgeConfiguration device) throws IOException {
47 logger.info("Connecting to RFXCOM at {}:{} over TCP/IP", device.host, device.port);
48 socket = new Socket(device.host, device.port);
49 socket.setSoTimeout(100); // In ms. Small values mean faster shutdown but more cpu usage.
50 in = socket.getInputStream();
51 out = socket.getOutputStream();
54 if (in.markSupported()) {
58 readerThread = new RFXComStreamReader(this, readerThreadName);
63 public void disconnect() {
64 logger.debug("Disconnecting");
66 if (readerThread != null) {
67 logger.debug("Interrupt stream listener");
68 readerThread.interrupt();
71 } catch (InterruptedException e) {
76 logger.debug("Close socket");
79 } catch (IOException e) {
80 logger.debug("Error while closing the socket: {}", e.getMessage());
89 logger.debug("Closed");
93 public void sendMessage(byte[] data) throws IOException {
94 if (logger.isTraceEnabled()) {
95 logger.trace("Send data (len={}): {}", data.length, HexUtils.bytesToHex(data));
102 int read(byte[] buffer, int offset, int length) throws IOException {
104 return super.read(buffer, offset, length);
105 } catch (SocketTimeoutException ignore) {
106 // ignore this exception, instead return 0 to behave like the serial read