2 * Copyright (c) 2010-2020 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.pulseaudio.internal;
15 import static org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants.*;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.PrintStream;
20 import java.net.Socket;
21 import java.net.SocketException;
22 import java.net.SocketTimeoutException;
23 import java.net.UnknownHostException;
24 import java.util.ArrayList;
25 import java.util.List;
27 import org.apache.commons.lang.StringUtils;
28 import org.openhab.binding.pulseaudio.internal.cli.Parser;
29 import org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig;
30 import org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig.State;
31 import org.openhab.binding.pulseaudio.internal.items.Module;
32 import org.openhab.binding.pulseaudio.internal.items.Sink;
33 import org.openhab.binding.pulseaudio.internal.items.SinkInput;
34 import org.openhab.binding.pulseaudio.internal.items.Source;
35 import org.openhab.binding.pulseaudio.internal.items.SourceOutput;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * The client connects to a pulseaudio server via TCP. It reads the current state of the
41 * pulseaudio server (available sinks, sources,...) and can send commands to the server.
42 * The syntax of the commands is the same as for the pactl command line tool provided by pulseaudio.
44 * On the pulseaudio server the module-cli-protocol-tcp has to be loaded.
46 * @author Tobias Bräutigam - Initial contribution
48 public class PulseaudioClient {
50 private final Logger logger = LoggerFactory.getLogger(PulseaudioClient.class);
54 private Socket client;
56 private List<AbstractAudioDeviceConfig> items;
57 private List<Module> modules;
60 * corresponding name to execute actions on sink items
62 private static final String ITEM_SINK = "sink";
65 * corresponding name to execute actions on source items
67 private static final String ITEM_SOURCE = "source";
70 * corresponding name to execute actions on sink-input items
72 private static final String ITEM_SINK_INPUT = "sink-input";
75 * corresponding name to execute actions on source-output items
77 private static final String ITEM_SOURCE_OUTPUT = "source-output";
80 * command to list the loaded modules
82 private static final String CMD_LIST_MODULES = "list-modules";
85 * command to list the sinks
87 private static final String CMD_LIST_SINKS = "list-sinks";
90 * command to list the sources
92 private static final String CMD_LIST_SOURCES = "list-sources";
95 * command to list the sink-inputs
97 private static final String CMD_LIST_SINK_INPUTS = "list-sink-inputs";
100 * command to list the source-outputs
102 private static final String CMD_LIST_SOURCE_OUTPUTS = "list-source-outputs";
105 * command to load a module
107 private static final String CMD_LOAD_MODULE = "load-module";
110 * command to unload a module
112 private static final String CMD_UNLOAD_MODULE = "unload-module";
115 * name of the module-combine-sink
117 private static final String MODULE_COMBINE_SINK = "module-combine-sink";
119 public PulseaudioClient() throws IOException {
120 this("localhost", 4712);
123 public PulseaudioClient(String host, int port) throws IOException {
127 items = new ArrayList<>();
128 modules = new ArrayList<>();
134 public boolean isConnected() {
135 return client.isConnected();
139 * updates the item states and their relationships
141 public void update() {
143 modules.addAll(Parser.parseModules(listModules()));
146 if (TYPE_FILTERS.get(SINK_THING_TYPE.getId())) {
147 logger.debug("reading sinks");
148 items.addAll(Parser.parseSinks(listSinks(), this));
150 if (TYPE_FILTERS.get(SOURCE_THING_TYPE.getId())) {
151 logger.debug("reading sources");
152 items.addAll(Parser.parseSources(listSources(), this));
154 if (TYPE_FILTERS.get(SINK_INPUT_THING_TYPE.getId())) {
155 logger.debug("reading sink-inputs");
156 items.addAll(Parser.parseSinkInputs(listSinkInputs(), this));
158 if (TYPE_FILTERS.get(SOURCE_OUTPUT_THING_TYPE.getId())) {
159 logger.debug("reading source-outputs");
160 items.addAll(Parser.parseSourceOutputs(listSourceOutputs(), this));
162 logger.debug("Pulseaudio server {}: {} modules and {} items updated", host, modules.size(), items.size());
165 private String listModules() {
166 return this.sendRawRequest(CMD_LIST_MODULES);
169 private String listSinks() {
170 return this.sendRawRequest(CMD_LIST_SINKS);
173 private String listSources() {
174 return this.sendRawRequest(CMD_LIST_SOURCES);
177 private String listSinkInputs() {
178 return this.sendRawRequest(CMD_LIST_SINK_INPUTS);
181 private String listSourceOutputs() {
182 return this.sendRawRequest(CMD_LIST_SOURCE_OUTPUTS);
186 * retrieves a module by its id
189 * @return the corresponding {@link Module} to the given <code>id</code>
191 public Module getModule(int id) {
192 for (Module module : modules) {
193 if (module.getId() == id) {
201 * send the command directly to the pulseaudio server
202 * for a list of available commands please take a look at
203 * http://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/User/CLI
207 public void sendCommand(String command) {
208 sendRawCommand(command);
212 * retrieves a {@link Sink} by its name
214 * @return the corresponding {@link Sink} to the given <code>name</code>
216 public Sink getSink(String name) {
217 for (AbstractAudioDeviceConfig item : items) {
218 if (item.getPaName().equalsIgnoreCase(name) && item instanceof Sink) {
226 * retrieves a {@link Sink} by its id
228 * @return the corresponding {@link Sink} to the given <code>id</code>
230 public Sink getSink(int id) {
231 for (AbstractAudioDeviceConfig item : items) {
232 if (item.getId() == id && item instanceof Sink) {
240 * retrieves a {@link SinkInput} by its name
242 * @return the corresponding {@link SinkInput} to the given <code>name</code>
244 public SinkInput getSinkInput(String name) {
245 for (AbstractAudioDeviceConfig item : items) {
246 if (item.getPaName().equalsIgnoreCase(name) && item instanceof SinkInput) {
247 return (SinkInput) item;
254 * retrieves a {@link SinkInput} by its id
256 * @return the corresponding {@link SinkInput} to the given <code>id</code>
258 public SinkInput getSinkInput(int id) {
259 for (AbstractAudioDeviceConfig item : items) {
260 if (item.getId() == id && item instanceof SinkInput) {
261 return (SinkInput) item;
268 * retrieves a {@link Source} by its name
270 * @return the corresponding {@link Source} to the given <code>name</code>
272 public Source getSource(String name) {
273 for (AbstractAudioDeviceConfig item : items) {
274 if (item.getPaName().equalsIgnoreCase(name) && item instanceof Source) {
275 return (Source) item;
282 * retrieves a {@link Source} by its id
284 * @return the corresponding {@link Source} to the given <code>id</code>
286 public Source getSource(int id) {
287 for (AbstractAudioDeviceConfig item : items) {
288 if (item.getId() == id && item instanceof Source) {
289 return (Source) item;
296 * retrieves a {@link SourceOutput} by its name
298 * @return the corresponding {@link SourceOutput} to the given <code>name</code>
300 public SourceOutput getSourceOutput(String name) {
301 for (AbstractAudioDeviceConfig item : items) {
302 if (item.getPaName().equalsIgnoreCase(name) && item instanceof SourceOutput) {
303 return (SourceOutput) item;
310 * retrieves a {@link SourceOutput} by its id
312 * @return the corresponding {@link SourceOutput} to the given <code>id</code>
314 public SourceOutput getSourceOutput(int id) {
315 for (AbstractAudioDeviceConfig item : items) {
316 if (item.getId() == id && item instanceof SourceOutput) {
317 return (SourceOutput) item;
324 * retrieves a {@link AbstractAudioDeviceConfig} by its name
326 * @return the corresponding {@link AbstractAudioDeviceConfig} to the given <code>name</code>
328 public AbstractAudioDeviceConfig getGenericAudioItem(String name) {
329 for (AbstractAudioDeviceConfig item : items) {
330 if (item.getPaName().equalsIgnoreCase(name)) {
337 public List<AbstractAudioDeviceConfig> getItems() {
342 * changes the <code>mute</code> state of the corresponding {@link Sink}
344 * @param item the {@link Sink} to handle
345 * @param mute mutes the sink if true, unmutes if false
347 public void setMute(AbstractAudioDeviceConfig item, boolean mute) {
351 String itemCommandName = getItemCommandName(item);
352 if (itemCommandName == null) {
355 String muteString = mute ? "1" : "0";
356 sendRawCommand("set-" + itemCommandName + "-mute " + item.getId() + " " + muteString);
357 // update internal data
362 * change the volume of a {@link AbstractAudioDeviceConfig}
364 * @param item the {@link AbstractAudioDeviceConfig} to handle
365 * @param vol the new volume value the {@link AbstractAudioDeviceConfig} should be changed to (possible values from
368 public void setVolume(AbstractAudioDeviceConfig item, int vol) {
372 String itemCommandName = getItemCommandName(item);
373 if (itemCommandName == null) {
376 sendRawCommand("set-" + itemCommandName + "-volume " + item.getId() + " " + vol);
377 item.setVolume(Math.round(100f / 65536f * vol));
381 * returns the item names that can be used in commands
386 private String getItemCommandName(AbstractAudioDeviceConfig item) {
387 if (item instanceof Sink) {
389 } else if (item instanceof Source) {
391 } else if (item instanceof SinkInput) {
392 return ITEM_SINK_INPUT;
393 } else if (item instanceof SourceOutput) {
394 return ITEM_SOURCE_OUTPUT;
400 * change the volume of a {@link AbstractAudioDeviceConfig}
402 * @param item the {@link AbstractAudioDeviceConfig} to handle
403 * @param vol the new volume percent value the {@link AbstractAudioDeviceConfig} should be changed to (possible
404 * values from 0 - 100)
406 public void setVolumePercent(AbstractAudioDeviceConfig item, int vol) {
411 vol = toAbsoluteVolume(vol);
413 setVolume(item, vol);
417 * transform a percent volume to a value that can be send to the pulseaudio server (0-65536)
422 private int toAbsoluteVolume(int percent) {
423 return (int) Math.round(65536f / 100f * Double.valueOf(percent));
427 * changes the combined sinks slaves to the given <code>sinks</code>
429 * @param combinedSink the combined sink which slaves should be changed
430 * @param sinks the list of new slaves
432 public void setCombinedSinkSlaves(Sink combinedSink, List<Sink> sinks) {
433 if (combinedSink == null || !combinedSink.isCombinedSink()) {
436 List<String> slaves = new ArrayList<>();
437 for (Sink sink : sinks) {
438 slaves.add(sink.getPaName());
440 // 1. delete old combined-sink
441 sendRawCommand(CMD_UNLOAD_MODULE + " " + combinedSink.getModule().getId());
442 // 2. add new combined-sink with same name and all slaves
443 sendRawCommand(CMD_LOAD_MODULE + " " + MODULE_COMBINE_SINK + " sink_name=" + combinedSink.getPaName()
444 + " slaves=" + StringUtils.join(slaves, ","));
445 // 3. update internal data structure because the combined sink has a new number + other slaves
450 * sets the sink a sink-input should be routed to
452 * @param sinkInput the sink-input to be rerouted
453 * @param sink the new sink the sink-input should be routed to
455 public void moveSinkInput(SinkInput sinkInput, Sink sink) {
456 if (sinkInput == null || sink == null) {
459 sendRawCommand("move-sink-input " + sinkInput.getId() + " " + sink.getId());
460 sinkInput.setSink(sink);
464 * sets the sink a source-output should be routed to
466 * @param sourceOutput the source-output to be rerouted
467 * @param source the new source the source-output should be routed to
469 public void moveSourceOutput(SourceOutput sourceOutput, Source source) {
470 if (sourceOutput == null || source == null) {
473 sendRawCommand("move-sink-input " + sourceOutput.getId() + " " + source.getId());
474 sourceOutput.setSource(source);
480 * @param source the source which state should be changed
481 * @param suspend suspend it or not
483 public void suspendSource(Source source, boolean suspend) {
484 if (source == null) {
488 sendRawCommand("suspend-source " + source.getId() + " 1");
489 source.setState(State.SUSPENDED);
491 sendRawCommand("suspend-source " + source.getId() + " 0");
492 // unsuspending the source could result in different states (RUNNING,IDLE,...)
493 // update to get the new state
501 * @param sink the sink which state should be changed
502 * @param suspend suspend it or not
504 public void suspendSink(Sink sink, boolean suspend) {
509 sendRawCommand("suspend-sink " + sink.getId() + " 1");
510 sink.setState(State.SUSPENDED);
512 sendRawCommand("suspend-sink " + sink.getId() + " 0");
513 // unsuspending the sink could result in different states (RUNNING,IDLE,...)
514 // update to get the new state
520 * changes the combined sinks slaves to the given <code>sinks</code>
522 * @param combinedSinkName the combined sink which slaves should be changed
523 * @param sinks the list of new slaves
525 public void setCombinedSinkSlaves(String combinedSinkName, List<Sink> sinks) {
526 if (getSink(combinedSinkName) != null) {
529 List<String> slaves = new ArrayList<>();
530 for (Sink sink : sinks) {
531 slaves.add(sink.getPaName());
533 // add new combined-sink with same name and all slaves
534 sendRawCommand(CMD_LOAD_MODULE + " " + MODULE_COMBINE_SINK + " sink_name=" + combinedSinkName + " slaves="
535 + StringUtils.join(slaves, ","));
536 // update internal data structure because the combined sink is new
540 private void sendRawCommand(String command) {
543 PrintStream out = new PrintStream(client.getOutputStream(), true);
544 logger.trace("sending command {} to pa-server {}", command, host);
545 out.print(command + "\r\n");
548 } catch (IOException e) {
549 logger.error("{}", e.getLocalizedMessage(), e);
553 private String sendRawRequest(String command) {
554 logger.trace("_sendRawRequest({})", command);
558 PrintStream out = new PrintStream(client.getOutputStream(), true);
559 out.print(command + "\r\n");
561 InputStream instr = client.getInputStream();
564 byte[] buff = new byte[1024];
568 retRead = instr.read(buff);
571 String line = new String(buff, 0, retRead);
572 // System.out.println("'"+line+"'");
573 if (line.endsWith(">>> ") && lc > 1) {
574 result += line.substring(0, line.length() - 4);
577 result += line.trim();
579 } while (retRead > 0);
580 } catch (SocketTimeoutException e) {
581 // Timeout -> as newer PA versions (>=5.0) do not send the >>> we have no chance
582 // to detect the end of the answer, except by this timeout
583 } catch (IOException e) {
584 logger.error("Exception while reading socket: {}", e.getMessage());
590 } catch (IOException e) {
591 logger.error("{}", e.getLocalizedMessage(), e);
596 private void checkConnection() {
597 if (client == null || client.isClosed() || !client.isConnected()) {
600 } catch (IOException e) {
601 logger.error("{}", e.getLocalizedMessage(), e);
607 * Connects to the pulseaudio server (timeout 500ms)
609 private void connect() throws IOException {
611 client = new Socket(host, port);
612 client.setSoTimeout(500);
613 } catch (UnknownHostException e) {
614 logger.error("unknown socket host {}", host);
615 } catch (SocketException e) {
616 logger.error("{}", e.getLocalizedMessage(), e);
621 * Disconnects from the pulseaudio server
623 public void disconnect() {
624 if (client != null) {
627 } catch (IOException e) {
628 logger.error("{}", e.getLocalizedMessage(), e);