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.atlona.internal.net;
15 import java.io.IOException;
16 import java.net.InetSocketAddress;
17 import java.nio.ByteBuffer;
18 import java.nio.channels.AsynchronousCloseException;
19 import java.nio.channels.SocketChannel;
20 import java.util.List;
21 import java.util.concurrent.ArrayBlockingQueue;
22 import java.util.concurrent.BlockingQueue;
23 import java.util.concurrent.CopyOnWriteArrayList;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicBoolean;
27 import java.util.concurrent.atomic.AtomicReference;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Represents a restartable socket connection to the underlying telnet session. Commands can be sent via
34 * {@link #sendCommand(String)} and responses will be received on any {@link SocketSessionListener}. This implementation
35 * of {@link SocketSession} communicates using a {@link SocketChannel} connection.
37 * @author Tim Roberts - Initial contribution
39 public class SocketChannelSession implements SocketSession {
40 private final Logger logger = LoggerFactory.getLogger(SocketChannelSession.class);
43 * The uid of the calling thing
45 private final String uid;
47 * The host/ip address to connect to
49 private final String host;
52 * The port to connect to
54 private final int port;
57 * The actual socket being used. Will be null if not connected
59 private final AtomicReference<SocketChannel> socketChannel = new AtomicReference<>();
62 * The {@link ResponseReader} that will be used to read from {@link #_readBuffer}
64 private final ResponseReader responseReader = new ResponseReader();
67 * The responses read from the {@link #responseReader}
69 private final BlockingQueue<Object> responses = new ArrayBlockingQueue<>(50);
72 * The dispatcher of responses from {@link #responses}
74 private final Dispatcher dispatcher = new Dispatcher();
77 * The {@link SocketSessionListener} that the {@link #dispatcher} will call
79 private List<SocketSessionListener> listeners = new CopyOnWriteArrayList<>();
82 * Creates the socket session from the given host and port
84 * @param uid the thing uid of the calling thing
85 * @param host a non-null, non-empty host/ip address
86 * @param port the port number between 1 and 65535
88 public SocketChannelSession(String uid, String host, int port) {
89 if (host == null || host.trim().length() == 0) {
90 throw new IllegalArgumentException("Host cannot be null or empty");
93 if (port < 1 || port > 65535) {
94 throw new IllegalArgumentException("Port must be between 1 and 65535");
102 public void addListener(SocketSessionListener listener) {
103 listeners.add(listener);
107 public void clearListeners() {
112 public boolean removeListener(SocketSessionListener listener) {
113 return listeners.remove(listener);
117 public void connect() throws IOException {
120 final SocketChannel channel = SocketChannel.open();
121 channel.configureBlocking(true);
123 logger.debug("Connecting to {}:{}", host, port);
124 channel.connect(new InetSocketAddress(host, port));
126 logger.debug("Waiting for connect");
127 while (!channel.finishConnect()) {
130 } catch (InterruptedException e) {
134 socketChannel.set(channel);
135 Thread dispatcherThread = new Thread(dispatcher, "OH-binding-" + uid + "-dispatcher");
136 dispatcherThread.setDaemon(true);
137 dispatcherThread.start();
138 Thread responseReaderThread = new Thread(responseReader, "OH-binding-" + uid + "-responseReader");
139 responseReaderThread.setDaemon(true);
140 responseReaderThread.start();
144 public void disconnect() throws IOException {
146 logger.debug("Disconnecting from {}:{}", host, port);
148 final SocketChannel channel = socketChannel.getAndSet(null);
151 dispatcher.stopRunning();
152 responseReader.stopRunning();
159 public boolean isConnected() {
160 final SocketChannel channel = socketChannel.get();
161 return channel != null && channel.isConnected();
165 public synchronized void sendCommand(String command) throws IOException {
166 if (!isConnected()) {
167 throw new IOException("Cannot send message - disconnected");
170 ByteBuffer toSend = ByteBuffer.wrap((command + "\r\n").getBytes());
172 final SocketChannel channel = socketChannel.get();
173 if (channel == null) {
174 logger.debug("Cannot send command '{}' - socket channel was closed", command);
176 logger.debug("Sending Command: '{}'", command);
177 channel.write(toSend);
182 * This is the runnable that will read from the socket and add messages to the responses queue (to be processed by
185 * @author Tim Roberts
188 private class ResponseReader implements Runnable {
191 * Whether the reader is currently running
193 private final AtomicBoolean isRunning = new AtomicBoolean(false);
196 * Locking to allow proper shutdown of the reader
198 private final CountDownLatch running = new CountDownLatch(1);
201 * Stops the reader. Will wait 5 seconds for the runnable to stop
203 public void stopRunning() {
204 if (isRunning.getAndSet(false)) {
206 if (!running.await(5, TimeUnit.SECONDS)) {
207 logger.warn("Waited too long for response reader to finish");
209 } catch (InterruptedException e) {
216 * Runs the logic to read from the socket until {@link #isRunning} is false. A 'response' is anything that ends
217 * with a carriage-return/newline combo. Additionally, the special "Login: " and "Password: " prompts are
218 * treated as responses for purposes of logging in.
222 final StringBuilder sb = new StringBuilder(100);
223 final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
228 while (isRunning.get()) {
230 // if reader is null, sleep and try again
231 if (readBuffer == null) {
236 final SocketChannel channel = socketChannel.get();
237 if (channel == null) {
239 isRunning.set(false);
243 int bytesRead = channel.read(readBuffer);
244 if (bytesRead == -1) {
245 responses.put(new IOException("server closed connection"));
246 isRunning.set(false);
248 } else if (bytesRead == 0) {
254 while (readBuffer.hasRemaining()) {
255 final char ch = (char) readBuffer.get();
257 if (ch == '\n' || ch == ' ') {
258 final String str = sb.toString();
259 if (str.endsWith("\r\n") || str.endsWith("Login: ") || str.endsWith("Password: ")) {
261 final String response = str.substring(0, str.length() - 2);
262 responses.put(response);
268 } catch (InterruptedException e) {
269 // Do nothing - probably shutting down
270 } catch (AsynchronousCloseException e) {
271 // socket was definitely closed by another thread
272 } catch (IOException e) {
274 isRunning.set(false);
276 } catch (InterruptedException e1) {
277 // Do nothing - probably shutting down
287 * The dispatcher runnable is responsible for reading the response queue and dispatching it to the current callable.
288 * Since the dispatcher is ONLY started when a callable is set, responses may pile up in the queue and be dispatched
289 * when a callable is set. Unlike the socket reader, this can be assigned to another thread (no state outside of the
292 * @author Tim Roberts
294 private class Dispatcher implements Runnable {
297 * Whether the dispatcher is running or not
299 private final AtomicBoolean isRunning = new AtomicBoolean(false);
302 * Locking to allow proper shutdown of the reader
304 private final CountDownLatch running = new CountDownLatch(1);
307 * Whether the dispatcher is currently processing a message
309 private final AtomicReference<Thread> processingThread = new AtomicReference<>();
312 * Stops the reader. Will wait 5 seconds for the runnable to stop (should stop within 1 second based on the poll
315 @SuppressWarnings("PMD.CompareObjectsWithEquals")
316 public void stopRunning() {
317 if (isRunning.getAndSet(false)) {
318 // only wait if stopRunning didn't get called as part of processing a message
319 // (which would happen if we are processing an exception that forced a session close)
320 final Thread processingThread = this.processingThread.get();
321 if (processingThread != null && Thread.currentThread() != processingThread) {
323 if (!running.await(5, TimeUnit.SECONDS)) {
324 logger.warn("Waited too long for dispatcher to finish");
326 } catch (InterruptedException e) {
334 * Runs the logic to dispatch any responses to the current listeners until {@link #isRunning} is false.
338 processingThread.set(Thread.currentThread());
341 while (isRunning.get()) {
343 // if no listeners, we don't want to start dispatching yet.
344 if (listeners.isEmpty()) {
349 final Object response = responses.poll(1, TimeUnit.SECONDS);
351 if (response != null) {
352 if (response instanceof String) {
354 logger.debug("Dispatching response: {}", response);
355 final SocketSessionListener[] listeners = SocketChannelSession.this.listeners
356 .toArray(new SocketSessionListener[0]);
357 for (SocketSessionListener listener : listeners) {
358 listener.responseReceived((String) response);
360 } catch (Exception e) {
361 logger.warn("Exception occurred processing the response '{}': ", response, e);
363 } else if (response instanceof Exception) {
364 logger.debug("Dispatching exception: {}", response);
365 final SocketSessionListener[] listeners = SocketChannelSession.this.listeners
366 .toArray(new SocketSessionListener[0]);
367 for (SocketSessionListener listener : listeners) {
368 listener.responseException((Exception) response);
371 logger.warn("Unknown response class: {}", response);
374 } catch (InterruptedException e) {
376 } catch (Exception e) {
377 logger.debug("Uncaught exception {}", e.getMessage(), e);
381 isRunning.set(false);
382 processingThread.set(null);