-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
MPDConnectionThread.java
309 lines (267 loc) · 10.6 KB
/
MPDConnectionThread.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/**
* Copyright (c) 2010-2024 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.mpd.internal.protocol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.mpd.internal.MPDException;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for communicating with the music player daemon through an IP connection
*
* @author Stefan Röllin - Initial contribution
*/
@NonNullByDefault
public class MPDConnectionThread extends Thread {
private static final int RECONNECTION_TIMEOUT_SEC = 60;
private final Logger logger = LoggerFactory.getLogger(MPDConnectionThread.class);
private final MPDResponseListener listener;
private final String address;
private final Integer port;
private final String password;
private @Nullable Socket socket = null;
private @Nullable InputStreamReader inputStreamReader = null;
private @Nullable BufferedReader reader = null;
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) {
this.listener = listener;
this.address = address;
this.port = port;
this.password = password;
setDaemon(true);
}
@Override
public void run() {
try {
while (!disposed.get()) {
try {
synchronized (pendingCommands) {
pendingCommands.add(new MPDCommand("status"));
pendingCommands.add(new MPDCommand("currentsong"));
}
establishConnection();
updateThingStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
processPendingCommands();
} catch (UnknownHostException e) {
updateThingStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Unknown host " + address);
} catch (IOException e) {
updateThingStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
} catch (MPDException e) {
updateThingStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
}
isInIdle.set(false);
closeSocket();
if (!disposed.get()) {
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) {
}
}
/**
* dispose the connection
*/
public void dispose() {
disposed.set(true);
Socket socket = this.socket;
if (socket != null) {
try {
socket.close();
} catch (IOException ignore) {
}
this.socket = null;
}
}
/**
* add a command to the pending commands queue
*
* @param command command to add
*/
public void addCommand(MPDCommand command) {
insertCommand(command, -1);
}
private void insertCommand(MPDCommand command, int position) {
logger.debug("insert command '{}' at position {}", command.getCommand(), position);
int index = position;
synchronized (pendingCommands) {
if (index < 0) {
index = pendingCommands.size();
}
pendingCommands.add(index, command);
sendNoIdleIfInIdle();
}
}
private void updateThingStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
if (!disposed.get()) {
listener.updateThingStatus(status, statusDetail, description);
}
}
private void sendNoIdleIfInIdle() {
if (isInIdle.compareAndSet(true, false)) {
try {
sendCommand(new MPDCommand("noidle"));
} catch (IOException e) {
logger.debug("sendCommand(noidle) failed", e);
}
}
}
private void establishConnection() throws UnknownHostException, IOException, MPDException {
openSocket();
MPDCommand currentCommand = new MPDCommand("connect");
MPDResponse response = readResponse(currentCommand);
if (!response.isOk()) {
throw new MPDException("Failed to connect to " + this.address + ":" + this.port);
}
if (!password.isEmpty()) {
currentCommand = new MPDCommand("password", password);
sendCommand(currentCommand);
response = readResponse(currentCommand);
if (!response.isOk()) {
throw new MPDException("Could not authenticate, please validate your password");
}
}
}
private void openSocket() throws UnknownHostException, IOException, MPDException {
logger.debug("opening connection to {} port {}", address, port);
if (address.isEmpty()) {
throw new MPDException("The parameter 'ipAddress' is missing.");
}
if (port < 1 || port > 65335) {
throw new MPDException("The parameter 'port' has an invalid value.");
}
Socket socket = new Socket(address, port);
inputStreamReader = new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8);
reader = new BufferedReader(inputStreamReader);
this.socket = socket;
}
private void processPendingCommands() throws IOException, MPDException {
MPDCommand currentCommand;
while (!disposed.get()) {
synchronized (pendingCommands) {
if (!pendingCommands.isEmpty()) {
currentCommand = pendingCommands.remove(0);
} else {
currentCommand = new MPDCommand("idle");
}
sendCommand(currentCommand);
if ("idle".equals(currentCommand.getCommand())) {
isInIdle.set(true);
}
}
MPDResponse response = readResponse(currentCommand);
if (!response.isOk()) {
insertCommand(new MPDCommand("clearerror"), 0);
}
listener.onResponse(response);
}
}
private void closeSocket() {
logger.debug("Closing socket");
BufferedReader reader = this.reader;
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
}
this.reader = null;
}
InputStreamReader inputStreamReader = this.inputStreamReader;
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException ignore) {
}
this.inputStreamReader = null;
}
Socket socket = this.socket;
if (socket != null) {
try {
socket.close();
} catch (IOException ignore) {
}
this.socket = null;
}
}
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();
socket.getOutputStream().write(line.getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().write('\n');
} else {
throw new IOException("Connection closed unexpectedly.");
}
}
private MPDResponse readResponse(MPDCommand command) throws IOException, MPDException {
logger.trace("read response for command '{}'", command.getCommand());
MPDResponse response = new MPDResponse(command.getCommand());
boolean done = false;
final BufferedReader reader = this.reader;
if (reader != null) {
while (!done) {
String line = reader.readLine();
logger.trace("received line '{}'", line);
if (line != null) {
if (line.startsWith("ACK [4")) {
logger.warn("command '{}' failed with permission error '{}'", command, line);
isInIdle.set(false);
throw new MPDException(
"Please validate your password and/or your permissions on the Music Player Daemon.");
} else if (line.startsWith("ACK")) {
logger.warn("command '{}' failed with '{}'", command, line);
response.setFailed();
done = true;
} else if (line.startsWith("OK")) {
done = true;
} else {
response.addLine(line.trim());
}
} else {
isInIdle.set(false);
throw new IOException("Communication failed unexpectedly.");
}
}
} else {
isInIdle.set(false);
throw new IOException("Connection closed unexpectedly.");
}
isInIdle.set(false);
return response;
}
}