Skip to content

Commit

Permalink
reconnect without loosing commands on broken idle connection (openhab…
Browse files Browse the repository at this point in the history
…#16299)

Signed-off-by: Christian Wicke <github@c.fg9.eu>
Signed-off-by: Jørgen Austvik <jaustvik@acm.org>
  • Loading branch information
christianwicke authored and austvik committed Mar 27, 2024
1 parent 7ef3b53 commit 3c5f81d
Showing 1 changed file with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public class MPDConnectionThread extends Thread {

private final List<MPDCommand> pendingCommands = new ArrayList<>();
private AtomicBoolean isInIdle = new AtomicBoolean(false);
private AtomicBoolean wakingUpFromIdle = new AtomicBoolean(false);
private AtomicBoolean disposed = new AtomicBoolean(false);

public MPDConnectionThread(MPDResponseListener listener, String address, Integer port, String password) {
Expand All @@ -70,7 +71,6 @@ public void run() {
while (!disposed.get()) {
try {
synchronized (pendingCommands) {
pendingCommands.clear();
pendingCommands.add(new MPDCommand("status"));
pendingCommands.add(new MPDCommand("currentsong"));
}
Expand All @@ -92,7 +92,16 @@ public void run() {
closeSocket();

if (!disposed.get()) {
sleep(RECONNECTION_TIMEOUT_SEC * 1000);
if (wakingUpFromIdle.compareAndSet(true, false)) {
logger.debug("reconnecting immediately and keeping pending commands");
} else {
logger.debug("reconnecting in {} seconds and clearing pending commands...",
RECONNECTION_TIMEOUT_SEC);
sleep(RECONNECTION_TIMEOUT_SEC * 1000);
synchronized (pendingCommands) {
pendingCommands.clear();
}
}
}
}
} catch (InterruptedException ignore) {
Expand Down Expand Up @@ -246,6 +255,7 @@ private void closeSocket() {

private void sendCommand(MPDCommand command) throws IOException {
logger.trace("send command '{}'", command);
wakingUpFromIdle.set("noidle".equals(command.getCommand()));
final Socket socket = this.socket;
if (socket != null) {
String line = command.asLine();
Expand Down

0 comments on commit 3c5f81d

Please sign in to comment.