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.nio.charset.StandardCharsets;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.benqprojector.internal.BenqProjectorException;
25 * Base class for BenQ projector communication.
27 * @author Michael Lobstein - Initial contribution
30 public interface BenqProjectorConnector {
31 static final int TIMEOUT_MS = 5 * 1000;
33 static final String START = "\r*";
34 static final String END = "#\r";
35 static final String BLANK = "";
38 * Procedure for connecting to projector.
40 * @throws BenqProjectorException
42 void connect() throws BenqProjectorException;
45 * Procedure for disconnecting to projector controller.
47 * @throws BenqProjectorException
49 void disconnect() throws BenqProjectorException;
52 * Procedure for sending raw data to projector.
57 * @throws BenqProjectorException
59 String sendMessage(String data) throws BenqProjectorException;
62 * Common method called by the Serial or Tcp connector to send the message to the projector, wait for a response and
63 * return it after processing.
68 * The connector's input stream.
70 * The connector's output stream.
72 * @throws BenqProjectorException
74 default String sendMsgReadResp(String data, @Nullable InputStream in, @Nullable OutputStream out)
75 throws IOException, BenqProjectorException {
78 if (in != null && out != null) {
79 out.write((START + data + END).getBytes(StandardCharsets.US_ASCII));
82 long startTime = System.currentTimeMillis();
85 while (elapsedTime < TIMEOUT_MS) {
86 int availableBytes = in.available();
87 if (availableBytes > 0) {
88 byte[] tmpData = new byte[availableBytes];
89 int readBytes = in.read(tmpData, 0, availableBytes);
90 resp = resp.concat(new String(tmpData, 0, readBytes, StandardCharsets.US_ASCII));
91 if (resp.contains(END)) {
92 return resp.replaceAll("[\\r\\n*#>]", BLANK).replace(data, BLANK);
97 } catch (InterruptedException e) {
98 throw new BenqProjectorException(e);
102 elapsedTime = System.currentTimeMillis() - startTime;