]> git.basschouten.com Git - openhab-addons.git/blob
1a41ac8188e1b78eadc8211162d159a2a365d97a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.sonyprojector.internal.communication.serial;
14
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;
21
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;
39
40 /**
41  * Class for communicating with Sony Projectors through a serial connection
42  *
43  * @author Laurent Garnier - Initial contribution
44  */
45 @NonNullByDefault
46 public class SonyProjectorSerialConnector extends SonyProjectorConnector implements SerialPortEventListener {
47
48     private final Logger logger = LoggerFactory.getLogger(SonyProjectorSerialConnector.class);
49
50     private static final int BAUD_RATE = 38400;
51     private static final long READ_TIMEOUT_MS = TimeUnit.MILLISECONDS.toMillis(3500);
52
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;
59
60     private String serialPortName;
61     private SerialPortManager serialPortManager;
62
63     private @Nullable SerialPort serialPort;
64
65     /**
66      * Constructor
67      *
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
71      */
72     public SonyProjectorSerialConnector(SerialPortManager serialPortManager, String serialPortName,
73             SonyProjectorModel model) {
74         this(serialPortManager, serialPortName, model, false);
75     }
76
77     /**
78      * Constructor
79      *
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
84      */
85     public SonyProjectorSerialConnector(SerialPortManager serialPortManager, String serialPortName,
86             SonyProjectorModel model, boolean simu) {
87         super(model, simu);
88
89         this.serialPortManager = serialPortManager;
90         this.serialPortName = serialPortName;
91     }
92
93     @Override
94     public synchronized void open() throws ConnectionException {
95         if (!connected) {
96             logger.debug("Opening serial connection on port {}", serialPortName);
97             try {
98                 SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(serialPortName);
99                 if (portIdentifier == null) {
100                     throw new ConnectionException("@text/exception.invalid-serial-port", serialPortName);
101                 }
102
103                 SerialPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
104
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);
110
111                 InputStream dataIn = commPort.getInputStream();
112                 OutputStream dataOut = commPort.getOutputStream();
113
114                 if (dataOut != null) {
115                     dataOut.flush();
116                 }
117                 if (dataIn != null && dataIn.markSupported()) {
118                     try {
119                         dataIn.reset();
120                     } catch (IOException e) {
121                     }
122                 }
123
124                 // RXTX serial port library causes high CPU load
125                 // Start event listener, which will just sleep and slow down event
126                 // loop
127                 try {
128                     commPort.addEventListener(this);
129                     commPort.notifyOnDataAvailable(true);
130                 } catch (TooManyListenersException e) {
131                     logger.debug("Too Many Listeners Exception: {}", e.getMessage(), e);
132                 }
133
134                 this.serialPort = commPort;
135                 this.dataIn = dataIn;
136                 this.dataOut = dataOut;
137
138                 connected = true;
139
140                 logger.debug("Serial connection opened");
141             } catch (PortInUseException | UnsupportedCommOperationException | IOException e) {
142                 throw new ConnectionException("@text/exception.opening-serial-connection-failed", e);
143             }
144         }
145     }
146
147     @Override
148     public synchronized void close() {
149         if (connected) {
150             logger.debug("Closing serial connection");
151             SerialPort serialPort = this.serialPort;
152             if (serialPort != null) {
153                 serialPort.removeEventListener();
154             }
155             super.close();
156             if (serialPort != null) {
157                 serialPort.close();
158                 this.serialPort = null;
159             }
160             connected = false;
161         }
162     }
163
164     @Override
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;
175         return message;
176     }
177
178     @Override
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];
186         int index = 0;
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));
192             if (len > 0) {
193                 for (int i = 0; i < len; i++) {
194                     if (dataBuffer[i] == START_CODE) {
195                         startCodeReached = true;
196                     }
197                     if (startCodeReached) {
198                         if (index < 8) {
199                             message[index++] = dataBuffer[i];
200                         }
201                         if (dataBuffer[i] == END_CODE) {
202                             endCodeReached = true;
203                         }
204                     }
205                 }
206             }
207             timeout = (System.currentTimeMillis() - startTimeRead) > READ_TIMEOUT_MS;
208         }
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");
212         }
213         logger.debug("readResponse: {}", HexUtils.bytesToHex(message));
214
215         return message;
216     }
217
218     @Override
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");
223         }
224
225         // Check START CODE
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");
230         }
231
232         // Check END CODE
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");
237         }
238
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");
244         }
245
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");
253             }
254         } else if (responseMessage[3] == TYPE_ACK) {
255             // ACK
256             byte[] errorCode = Arrays.copyOfRange(responseMessage, 1, 3);
257             if (!Arrays.equals(errorCode, SonyProjectorSerialError.COMPLETE.getDataCode())) {
258                 String msg = "KO";
259                 try {
260                     SonyProjectorSerialError error = SonyProjectorSerialError.getFromDataCode(errorCode);
261                     msg = error.getMessage();
262                 } catch (CommunicationException e) {
263                 }
264                 logger.debug("{} received in response", msg);
265                 throw new CommunicationException(msg + " received in response");
266             }
267         } else {
268             logger.debug("Unexpected TYPE in response: {}", Integer.toHexString(responseMessage[3] & 0x000000FF));
269             throw new CommunicationException("Unexpected TYPE in response");
270         }
271     }
272
273     private byte computeCheckSum(byte[] message) {
274         byte result = 0;
275         for (int i = 1; i <= 5; i++) {
276             result |= (message[i] & 0x000000FF);
277         }
278         return result;
279     }
280
281     @Override
282     protected byte[] getResponseData(byte[] responseMessage) {
283         return Arrays.copyOfRange(responseMessage, 4, 6);
284     }
285
286     @Override
287     public void serialEvent(SerialPortEvent serialPortEvent) {
288         try {
289             logger.debug("RXTX library CPU load workaround, sleep forever");
290             Thread.sleep(Long.MAX_VALUE);
291         } catch (InterruptedException e) {
292             Thread.currentThread().interrupt();
293         }
294     }
295 }