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.oppo.internal.communication;
15 import static org.openhab.binding.oppo.internal.OppoBindingConstants.*;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.OutputStream;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.oppo.internal.OppoException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Abstract class for communicating with the Oppo player
35 * @author Laurent Garnier - Initial contribution
36 * @author Michael Lobstein - Adapted for the Oppo binding
39 public abstract class OppoConnector {
40 private static final Pattern QRY_PATTERN = Pattern.compile("^@(Q[A-Z0-9]{2}|VUP|VDN) OK (.*)$");
41 private static final Pattern STUS_PATTERN = Pattern.compile("^@(U[A-Z0-9]{2}) (.*)$");
43 private static final String OK_ON = "@OK ON";
44 private static final String OK_OFF = "@OK OFF";
45 private static final String NOP_OK = "@NOP OK";
46 private static final String NOP = "NOP";
47 private static final String OK = "OK";
49 private final Logger logger = LoggerFactory.getLogger(OppoConnector.class);
51 private String beginCmd = "#";
52 private String endCmd = "\r";
54 /** The output stream */
55 protected @Nullable OutputStream dataOut;
57 /** The input stream */
58 protected @Nullable InputStream dataIn;
60 /** true if the connection is established, false if not */
61 private boolean connected;
63 private @Nullable Thread readerThread;
65 private final List<OppoMessageEventListener> listeners = new ArrayList<>();
68 * Called when using direct IP connection for 83/93/95/103/105
69 * overrides the command message preamble and removes the CR at the end
71 public void overrideCmdPreamble(boolean override) {
73 this.beginCmd = "REMOTE ";
79 * Get whether the connection is established or not
81 * @return true if the connection is established
83 public boolean isConnected() {
88 * Set whether the connection is established or not
90 * @param connected true if the connection is established
92 protected void setConnected(boolean connected) {
93 this.connected = connected;
97 * Set the thread that handles the feedback messages
99 * @param readerThread the thread
101 protected void setReaderThread(Thread readerThread) {
102 this.readerThread = readerThread;
106 * Open the connection with the Oppo player
108 * @throws OppoException - In case of any problem
110 public abstract void open() throws OppoException;
113 * Close the connection with the Oppo player
115 public abstract void close();
118 * Stop the thread that handles the feedback messages and close the opened input and output streams
120 protected void cleanup() {
121 Thread readerThread = this.readerThread;
122 OutputStream dataOut = this.dataOut;
123 if (dataOut != null) {
126 } catch (IOException e) {
127 logger.debug("Error closing dataOut: {}", e.getMessage());
131 InputStream dataIn = this.dataIn;
132 if (dataIn != null) {
135 } catch (IOException e) {
136 logger.debug("Error closing dataIn: {}", e.getMessage());
140 if (readerThread != null) {
141 readerThread.interrupt();
142 this.readerThread = null;
144 readerThread.join(3000);
145 } catch (InterruptedException e) {
146 logger.warn("Error joining readerThread: {}", e.getMessage());
152 * Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes
153 * actually read is returned as an integer.
155 * @param dataBuffer the buffer into which the data is read.
157 * @return the total number of bytes read into the buffer, or -1 if there is no more data because the end of the
158 * stream has been reached.
160 * @throws OppoException - If the input stream is null, if the first byte cannot be read for any reason
161 * other than the end of the file, if the input stream has been closed, or if some other I/O error
164 protected int readInput(byte[] dataBuffer) throws OppoException {
165 InputStream dataIn = this.dataIn;
166 if (dataIn == null) {
167 throw new OppoException("readInput failed: input stream is null");
170 return dataIn.read(dataBuffer);
171 } catch (IOException e) {
172 throw new OppoException("readInput failed: " + e.getMessage(), e);
177 * Request the Oppo controller to execute a command and pass in a value
179 * @param cmd the command to execute
180 * @param value the string value to pass with the command
182 * @throws OppoException - In case of any problem
184 public void sendCommand(OppoCommand cmd, @Nullable String value) throws OppoException {
185 sendCommand(cmd.getValue() + " " + value);
189 * Request the Oppo controller to execute a command that does not specify a value
191 * @param cmd the command to execute
193 * @throws OppoException - In case of any problem
195 public void sendCommand(OppoCommand cmd) throws OppoException {
196 sendCommand(cmd.getValue());
200 * Request the Oppo controller to execute a raw command string
202 * @param command the command string to run
204 * @throws OppoException - In case of any problem
206 public void sendCommand(String command) throws OppoException {
207 String messageStr = beginCmd + command + endCmd;
208 logger.debug("Sending command: {}", messageStr);
210 OutputStream dataOut = this.dataOut;
211 if (dataOut == null) {
212 throw new OppoException("Send command \"" + messageStr + "\" failed: output stream is null");
215 dataOut.write(messageStr.getBytes(StandardCharsets.US_ASCII));
217 } catch (IOException e) {
218 logger.debug("Send command \"{}\" failed: {}", messageStr, e.getMessage());
219 throw new OppoException("Send command \"" + command + "\" failed: " + e.getMessage(), e);
224 * Add a listener to the list of listeners to be notified with events
226 * @param listener the listener
228 public void addEventListener(OppoMessageEventListener listener) {
229 listeners.add(listener);
233 * Remove a listener from the list of listeners to be notified with events
235 * @param listener the listener
237 public void removeEventListener(OppoMessageEventListener listener) {
238 listeners.remove(listener);
242 * Analyze an incoming message and dispatch corresponding (key, value) to the event listeners
244 * @param incomingMessage the received message
246 public void handleIncomingMessage(byte[] incomingMessage) {
247 String message = new String(incomingMessage, StandardCharsets.US_ASCII).trim();
249 logger.debug("handleIncomingMessage: {}", message);
251 if (NOP_OK.equals(message)) {
252 dispatchKeyValue(NOP, OK);
256 // Before verbose mode 2 & 3 get set, these are the responses to QPW
257 if (OK_ON.equals(message)) {
258 dispatchKeyValue(QPW, ON);
262 if (OK_OFF.equals(message)) {
263 dispatchKeyValue(QPW, OFF);
267 // Player sent an OK response to a query: @QDT OK DVD-VIDEO or a volume update @VUP OK 100
268 Matcher matcher = QRY_PATTERN.matcher(message);
269 if (matcher.find()) {
270 // pull out the inquiry type and the remainder of the message
271 dispatchKeyValue(matcher.group(1), matcher.group(2));
275 // Player sent a status update ie: @UTC 000 000 T 00:00:01
276 matcher = STUS_PATTERN.matcher(message);
277 if (matcher.find()) {
278 // pull out the update type and the remainder of the message
279 dispatchKeyValue(matcher.group(1), matcher.group(2));
283 logger.debug("unhandled message: {}", message);
287 * Dispatch an event (key, value) to the event listeners
290 * @param value the value
292 private void dispatchKeyValue(String key, String value) {
293 OppoMessageEvent event = new OppoMessageEvent(this, key, value);
294 listeners.forEach(l -> l.onNewMessageEvent(event));