]> git.basschouten.com Git - openhab-addons.git/blob
86793e3d8005959d05abce0722bf7cea908f19c9
[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.russound.internal.net;
14
15 import java.io.IOException;
16 import java.util.concurrent.ArrayBlockingQueue;
17 import java.util.concurrent.BlockingQueue;
18 import java.util.concurrent.TimeUnit;
19
20 /**
21  * Implementation of {@link SocketSessionListener} that allows a caller to wait for a response via
22  * {@link #getResponse()}
23  *
24  * @author Tim Roberts - Initial contribution
25  */
26 public class WaitingSessionListener implements SocketSessionListener {
27
28     /**
29      * Cache of responses that have occurred
30      */
31     private BlockingQueue<Object> responses = new ArrayBlockingQueue<>(5);
32
33     /**
34      * Will return the next response from {@link #responses}. If the response is an exception, that exception will
35      * be thrown instead.
36      *
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
40      */
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 stringCommand) {
48             return stringCommand;
49         } else if (lastResponse instanceof IOException ioException) {
50             throw ioException;
51         } else if (lastResponse == null) {
52             throw new IOException("Didn't receive response in time");
53         } else {
54             return lastResponse.toString();
55         }
56     }
57
58     @Override
59     public void responseReceived(String response) throws InterruptedException {
60         responses.put(response);
61     }
62
63     @Override
64     public void responseException(IOException e) throws InterruptedException {
65         responses.put(e);
66     }
67 }