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.sonyprojector.internal.communication.serial;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18 import java.util.Arrays;
19 import java.util.TooManyListenersException;
20 import java.util.concurrent.TimeUnit;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.sonyprojector.internal.SonyProjectorModel;
25 import org.openhab.binding.sonyprojector.internal.communication.SonyProjectorConnector;
26 import org.openhab.binding.sonyprojector.internal.communication.SonyProjectorItem;
27 import org.openhab.core.i18n.CommunicationException;
28 import org.openhab.core.i18n.ConnectionException;
29 import org.openhab.core.io.transport.serial.PortInUseException;
30 import org.openhab.core.io.transport.serial.SerialPort;
31 import org.openhab.core.io.transport.serial.SerialPortEvent;
32 import org.openhab.core.io.transport.serial.SerialPortEventListener;
33 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
34 import org.openhab.core.io.transport.serial.SerialPortManager;
35 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
36 import org.openhab.core.util.HexUtils;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
41 * Class for communicating with Sony Projectors through a serial connection
43 * @author Laurent Garnier - Initial contribution
46 public class SonyProjectorSerialConnector extends SonyProjectorConnector implements SerialPortEventListener {
48 private final Logger logger = LoggerFactory.getLogger(SonyProjectorSerialConnector.class);
50 private static final int BAUD_RATE = 38400;
51 private static final long READ_TIMEOUT_MS = TimeUnit.MILLISECONDS.toMillis(3500);
53 protected static final byte START_CODE = (byte) 0xA9;
54 protected static final byte END_CODE = (byte) 0x9A;
55 private static final byte GET = (byte) 0x01;
56 private static final byte SET = (byte) 0x00;
57 protected static final byte TYPE_ACK = (byte) 0x03;
58 private static final byte TYPE_ITEM = (byte) 0x02;
60 private String serialPortName;
61 private SerialPortManager serialPortManager;
63 private @Nullable SerialPort serialPort;
68 * @param serialPortManager the serial port manager
69 * @param serialPortName the serial port name to be used
70 * @param model the projector model in use
72 public SonyProjectorSerialConnector(SerialPortManager serialPortManager, String serialPortName,
73 SonyProjectorModel model) {
74 this(serialPortManager, serialPortName, model, false);
80 * @param serialPortManager the serial port manager
81 * @param serialPortName the serial port name to be used
82 * @param model the projector model in use
83 * @param simu whether the communication is simulated or real
85 public SonyProjectorSerialConnector(SerialPortManager serialPortManager, String serialPortName,
86 SonyProjectorModel model, boolean simu) {
89 this.serialPortManager = serialPortManager;
90 this.serialPortName = serialPortName;
94 public synchronized void open() throws ConnectionException {
96 logger.debug("Opening serial connection on port {}", serialPortName);
98 SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(serialPortName);
99 if (portIdentifier == null) {
100 throw new ConnectionException("@text/exception.invalid-serial-port", serialPortName);
103 SerialPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
105 commPort.setSerialPortParams(BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
106 SerialPort.PARITY_EVEN);
107 commPort.enableReceiveThreshold(8);
108 commPort.enableReceiveTimeout(100);
109 commPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
111 InputStream dataIn = commPort.getInputStream();
112 OutputStream dataOut = commPort.getOutputStream();
114 if (dataOut != null) {
117 if (dataIn != null && dataIn.markSupported()) {
120 } catch (IOException e) {
124 // RXTX serial port library causes high CPU load
125 // Start event listener, which will just sleep and slow down event
128 commPort.addEventListener(this);
129 commPort.notifyOnDataAvailable(true);
130 } catch (TooManyListenersException e) {
131 logger.debug("Too Many Listeners Exception: {}", e.getMessage(), e);
134 this.serialPort = commPort;
135 this.dataIn = dataIn;
136 this.dataOut = dataOut;
140 logger.debug("Serial connection opened");
141 } catch (PortInUseException | UnsupportedCommOperationException | IOException e) {
142 throw new ConnectionException("@text/exception.opening-serial-connection-failed", e);
148 public synchronized void close() {
150 logger.debug("Closing serial connection");
151 SerialPort serialPort = this.serialPort;
152 if (serialPort != null) {
153 serialPort.removeEventListener();
156 if (serialPort != null) {
158 this.serialPort = null;
165 protected byte[] buildMessage(SonyProjectorItem item, boolean getCommand, byte[] data) {
166 byte[] message = new byte[8];
167 message[0] = START_CODE;
168 message[1] = item.getCode()[0];
169 message[2] = item.getCode()[1];
170 message[3] = getCommand ? GET : SET;
171 message[4] = data[0];
172 message[5] = data[1];
173 message[6] = computeCheckSum(message);
174 message[7] = END_CODE;
179 protected synchronized byte[] readResponse() throws CommunicationException {
180 logger.debug("readResponse (timeout = {} ms)...", READ_TIMEOUT_MS);
181 byte[] message = new byte[8];
182 boolean startCodeReached = false;
183 boolean endCodeReached = false;
184 boolean timeout = false;
185 byte[] dataBuffer = new byte[8];
187 long startTimeRead = System.currentTimeMillis();
188 while (!endCodeReached && !timeout) {
189 logger.trace("readResponse readInput...");
190 int len = readInput(dataBuffer);
191 logger.trace("readResponse readInput {} => {}", len, HexUtils.bytesToHex(dataBuffer));
193 for (int i = 0; i < len; i++) {
194 if (dataBuffer[i] == START_CODE) {
195 startCodeReached = true;
197 if (startCodeReached) {
199 message[index++] = dataBuffer[i];
201 if (dataBuffer[i] == END_CODE) {
202 endCodeReached = true;
207 timeout = (System.currentTimeMillis() - startTimeRead) > READ_TIMEOUT_MS;
209 if (!endCodeReached && timeout) {
210 logger.debug("readResponse timeout: only {} bytes read after {} ms", index, READ_TIMEOUT_MS);
211 throw new CommunicationException("readResponse failed: timeout");
213 logger.debug("readResponse: {}", HexUtils.bytesToHex(message));
219 protected void validateResponse(byte[] responseMessage, SonyProjectorItem item) throws CommunicationException {
220 if (responseMessage.length != 8) {
221 logger.debug("Unexpected response data length: {}", responseMessage.length);
222 throw new CommunicationException("Unexpected response data length");
226 if (responseMessage[0] != START_CODE) {
227 logger.debug("Unexpected message START CODE in response: {} rather than {}",
228 Integer.toHexString(responseMessage[0] & 0x000000FF), Integer.toHexString(START_CODE & 0x000000FF));
229 throw new CommunicationException("Unexpected message START CODE in response");
233 if (responseMessage[7] != END_CODE) {
234 logger.debug("Unexpected message END CODE in response: {} rather than {}",
235 Integer.toHexString(responseMessage[7] & 0x000000FF), Integer.toHexString(END_CODE & 0x000000FF));
236 throw new CommunicationException("Unexpected message END CODE in response");
239 byte checksum = computeCheckSum(responseMessage);
240 if (responseMessage[6] != checksum) {
241 logger.debug("Invalid check sum in response: {} rather than {}",
242 Integer.toHexString(responseMessage[6] & 0x000000FF), Integer.toHexString(checksum & 0x000000FF));
243 throw new CommunicationException("Invalid check sum in response");
246 if (responseMessage[3] == TYPE_ITEM) {
247 // Item number should be the same as used for sending
248 byte[] itemResponseMsg = Arrays.copyOfRange(responseMessage, 1, 3);
249 if (!Arrays.equals(itemResponseMsg, item.getCode())) {
250 logger.debug("Unexpected item number in response: {} rather than {}",
251 HexUtils.bytesToHex(itemResponseMsg), HexUtils.bytesToHex(item.getCode()));
252 throw new CommunicationException("Unexpected item number in response");
254 } else if (responseMessage[3] == TYPE_ACK) {
256 byte[] errorCode = Arrays.copyOfRange(responseMessage, 1, 3);
257 if (!Arrays.equals(errorCode, SonyProjectorSerialError.COMPLETE.getDataCode())) {
260 SonyProjectorSerialError error = SonyProjectorSerialError.getFromDataCode(errorCode);
261 msg = error.getMessage();
262 } catch (CommunicationException e) {
264 logger.debug("{} received in response", msg);
265 throw new CommunicationException(msg + " received in response");
268 logger.debug("Unexpected TYPE in response: {}", Integer.toHexString(responseMessage[3] & 0x000000FF));
269 throw new CommunicationException("Unexpected TYPE in response");
273 private byte computeCheckSum(byte[] message) {
275 for (int i = 1; i <= 5; i++) {
276 result |= (message[i] & 0x000000FF);
282 protected byte[] getResponseData(byte[] responseMessage) {
283 return Arrays.copyOfRange(responseMessage, 4, 6);
287 public void serialEvent(SerialPortEvent serialPortEvent) {
289 logger.debug("RXTX library CPU load workaround, sleep forever");
290 Thread.sleep(Long.MAX_VALUE);
291 } catch (InterruptedException e) {
292 Thread.currentThread().interrupt();