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.russound.internal.net;
15 import java.io.IOException;
16 import java.util.concurrent.ArrayBlockingQueue;
17 import java.util.concurrent.BlockingQueue;
18 import java.util.concurrent.TimeUnit;
21 * Implementation of {@link SocketSessionListener} that allows a caller to wait for a response via
22 * {@link #getResponse()}
24 * @author Tim Roberts - Initial contribution
26 public class WaitingSessionListener implements SocketSessionListener {
29 * Cache of responses that have occurred
31 private BlockingQueue<Object> responses = new ArrayBlockingQueue<>(5);
34 * Will return the next response from {@link #responses}. If the response is an exception, that exception will
37 * @return a non-null, possibly empty response
38 * @throws IOException an IO exception occurred during reading
39 * @throws InterruptedException an interrupted exception occurred during reading
41 public String getResponse() throws IOException, InterruptedException {
42 // note: russound is inherently single threaded even though it accepts multiple connections
43 // if we have another thread sending a lot of commands (such as during startup), our response
44 // will not come in until the other commands have been processed. So we need a large wait
45 // time for it to be sent to us
46 final Object lastResponse = responses.poll(60, TimeUnit.SECONDS);
47 if (lastResponse instanceof String) {
48 return (String) lastResponse;
49 } else if (lastResponse instanceof IOException) {
50 throw (IOException) lastResponse;
51 } else if (lastResponse == null) {
52 throw new IOException("Didn't receive response in time");
54 return lastResponse.toString();
59 public void responseReceived(String response) throws InterruptedException {
60 responses.put(response);
64 public void responseException(IOException e) throws InterruptedException {