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.benqprojector.internal.connector;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18 import java.net.Socket;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.benqprojector.internal.BenqProjectorException;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * Connector for TCP communication.
29 * @author Michael Lobstein - Initial contribution
32 public class BenqProjectorTcpConnector implements BenqProjectorConnector {
34 private final Logger logger = LoggerFactory.getLogger(BenqProjectorTcpConnector.class);
35 private final String ip;
36 private final int port;
38 private @Nullable Socket socket = null;
39 private @Nullable InputStream in = null;
40 private @Nullable OutputStream out = null;
42 public BenqProjectorTcpConnector(String ip, int port) {
48 public void connect() throws BenqProjectorException {
49 logger.debug("Open connection to address'{}:{}'", ip, port);
52 Socket socket = new Socket(ip, port);
54 in = socket.getInputStream();
55 out = socket.getOutputStream();
56 } catch (IOException e) {
57 throw new BenqProjectorException(e);
62 public void disconnect() throws BenqProjectorException {
63 OutputStream out = this.out;
66 logger.debug("Close tcp out stream");
69 } catch (IOException e) {
70 logger.debug("Error occurred when closing tcp out stream: {}", e.getMessage());
74 InputStream in = this.in;
76 logger.debug("Close tcp in stream");
79 } catch (IOException e) {
80 logger.debug("Error occurred when closing tcp in stream: {}", e.getMessage());
84 Socket socket = this.socket;
86 logger.debug("Closing socket");
89 } catch (IOException e) {
90 logger.debug("Error occurred when closing tcp socket: {}", e.getMessage());
98 logger.debug("Closed");
102 public String sendMessage(String data) throws BenqProjectorException {
103 InputStream in = this.in;
104 OutputStream out = this.out;
106 if (in == null || out == null) {
114 // flush input stream
115 if (in.markSupported()) {
118 while (in.available() > 0) {
119 int availableBytes = in.available();
121 if (availableBytes > 0) {
122 byte[] tmpData = new byte[availableBytes];
123 in.read(tmpData, 0, availableBytes);
127 return sendMsgReadResp(data, in, out);
131 } catch (IOException e) {
132 logger.debug("IO error occurred...reconnect and resend once: {}", e.getMessage());
137 return sendMsgReadResp(data, in, out);
138 } catch (IOException e1) {
139 throw new BenqProjectorException(e);