2 * Copyright (c) 2010-2022 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.handler;
15 import static org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants.*;
17 import java.io.IOException;
18 import java.math.BigDecimal;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Hashtable;
22 import java.util.List;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.pulseaudio.internal.PulseAudioAudioSink;
34 import org.openhab.binding.pulseaudio.internal.PulseAudioAudioSource;
35 import org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants;
36 import org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig;
37 import org.openhab.binding.pulseaudio.internal.items.Sink;
38 import org.openhab.binding.pulseaudio.internal.items.SinkInput;
39 import org.openhab.binding.pulseaudio.internal.items.Source;
40 import org.openhab.core.audio.AudioFormat;
41 import org.openhab.core.audio.AudioSink;
42 import org.openhab.core.audio.AudioSource;
43 import org.openhab.core.config.core.Configuration;
44 import org.openhab.core.library.types.DecimalType;
45 import org.openhab.core.library.types.IncreaseDecreaseType;
46 import org.openhab.core.library.types.OnOffType;
47 import org.openhab.core.library.types.PercentType;
48 import org.openhab.core.library.types.StringType;
49 import org.openhab.core.thing.Bridge;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingTypeUID;
54 import org.openhab.core.thing.ThingUID;
55 import org.openhab.core.thing.binding.BaseThingHandler;
56 import org.openhab.core.thing.binding.ThingHandler;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.RefreshType;
59 import org.openhab.core.types.State;
60 import org.openhab.core.types.UnDefType;
61 import org.osgi.framework.BundleContext;
62 import org.osgi.framework.ServiceRegistration;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
67 * The {@link PulseaudioHandler} is responsible for handling commands, which are
68 * sent to one of the channels.
70 * @author Tobias Bräutigam - Initial contribution
71 * @author Miguel Álvarez - Register audio source and refactor
74 public class PulseaudioHandler extends BaseThingHandler implements DeviceStatusListener {
76 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
77 .unmodifiableSet(Stream.of(SINK_THING_TYPE, COMBINED_SINK_THING_TYPE, SINK_INPUT_THING_TYPE,
78 SOURCE_THING_TYPE, SOURCE_OUTPUT_THING_TYPE).collect(Collectors.toSet()));
79 private final Logger logger = LoggerFactory.getLogger(PulseaudioHandler.class);
80 private final int refresh = 60; // refresh every minute as default
82 private @Nullable PulseaudioBridgeHandler bridgeHandler;
83 private @Nullable String name;
84 private @Nullable ScheduledFuture<?> refreshJob;
85 private @Nullable PulseAudioAudioSink audioSink;
86 private @Nullable PulseAudioAudioSource audioSource;
87 private @Nullable Integer savedVolume;
89 private final Map<String, ServiceRegistration<AudioSink>> audioSinkRegistrations = new ConcurrentHashMap<>();
90 private final Map<String, ServiceRegistration<AudioSource>> audioSourceRegistrations = new ConcurrentHashMap<>();
92 private final BundleContext bundleContext;
94 public PulseaudioHandler(Thing thing, BundleContext bundleContext) {
96 this.bundleContext = bundleContext;
100 public void initialize() {
101 Configuration config = getThing().getConfiguration();
102 name = (String) config.get(DEVICE_PARAMETER_NAME);
104 // until we get an update put the Thing offline
105 updateStatus(ThingStatus.OFFLINE);
106 deviceOnlineWatchdog();
108 // if it's a SINK thing, then maybe we have to activate the audio sink
109 if (PulseaudioBindingConstants.SINK_THING_TYPE.equals(thing.getThingTypeUID())) {
110 // check the property to see if we it's enabled :
111 Boolean sinkActivated = (Boolean) thing.getConfiguration()
112 .get(PulseaudioBindingConstants.DEVICE_PARAMETER_AUDIO_SINK_ACTIVATION);
113 if (sinkActivated != null && sinkActivated) {
117 // if it's a SOURCE thing, then maybe we have to activate the audio source
118 if (SOURCE_THING_TYPE.equals(thing.getThingTypeUID())) {
119 // check the property to see if we it's enabled :
120 Boolean sourceActivated = (Boolean) thing.getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_ACTIVATION);
121 if (sourceActivated != null && sourceActivated) {
127 private void audioSinkSetup() {
128 final PulseaudioHandler thisHandler = this;
129 scheduler.submit(new Runnable() {
132 // Register the sink as an audio sink in openhab
133 logger.trace("Registering an audio sink for pulse audio sink thing {}", thing.getUID());
134 PulseAudioAudioSink audioSink = new PulseAudioAudioSink(thisHandler, scheduler);
135 setAudioSink(audioSink);
137 audioSink.connectIfNeeded();
138 } catch (IOException e) {
139 logger.warn("pulseaudio binding cannot connect to the module-simple-protocol-tcp on {} ({})",
140 getHost(), e.getMessage());
141 } catch (InterruptedException i) {
142 logger.info("Interrupted during sink audio connection: {}", i.getMessage());
145 audioSink.scheduleDisconnect();
147 @SuppressWarnings("unchecked")
148 ServiceRegistration<AudioSink> reg = (ServiceRegistration<AudioSink>) bundleContext
149 .registerService(AudioSink.class.getName(), audioSink, new Hashtable<>());
150 audioSinkRegistrations.put(thing.getUID().toString(), reg);
155 private void audioSourceSetup() {
156 final PulseaudioHandler thisHandler = this;
157 scheduler.submit(new Runnable() {
160 // Register the source as an audio source in openhab
161 logger.trace("Registering an audio source for pulse audio source thing {}", thing.getUID());
162 PulseAudioAudioSource audioSource = new PulseAudioAudioSource(thisHandler, scheduler);
163 setAudioSource(audioSource);
165 audioSource.connectIfNeeded();
166 } catch (IOException e) {
167 logger.warn("pulseaudio binding cannot connect to the module-simple-protocol-tcp on {} ({})",
168 getHost(), e.getMessage());
169 } catch (InterruptedException i) {
170 logger.info("Interrupted during source audio connection: {}", i.getMessage());
173 audioSource.scheduleDisconnect();
175 @SuppressWarnings("unchecked")
176 ServiceRegistration<AudioSource> reg = (ServiceRegistration<AudioSource>) bundleContext
177 .registerService(AudioSource.class.getName(), audioSource, new Hashtable<>());
178 audioSourceRegistrations.put(thing.getUID().toString(), reg);
184 public void dispose() {
185 if (refreshJob != null && !refreshJob.isCancelled()) {
186 refreshJob.cancel(true);
189 updateStatus(ThingStatus.OFFLINE);
190 if (bridgeHandler != null) {
191 bridgeHandler.unregisterDeviceStatusListener(this);
192 bridgeHandler = null;
194 logger.trace("Thing {} {} disposed.", getThing().getUID(), name);
196 if (audioSink != null) {
197 audioSink.disconnect();
199 if (audioSource != null) {
200 audioSource.disconnect();
202 // Unregister the potential pulse audio sink's audio sink
203 ServiceRegistration<AudioSink> sinkReg = audioSinkRegistrations.remove(getThing().getUID().toString());
204 if (sinkReg != null) {
205 logger.trace("Unregistering the audio sync service for pulse audio sink thing {}", getThing().getUID());
206 sinkReg.unregister();
208 // Unregister the potential pulse audio source's audio sources
209 ServiceRegistration<AudioSource> sourceReg = audioSourceRegistrations.remove(getThing().getUID().toString());
210 if (sourceReg != null) {
211 logger.trace("Unregistering the audio sync service for pulse audio source thing {}", getThing().getUID());
212 sourceReg.unregister();
216 private void deviceOnlineWatchdog() {
217 Runnable runnable = () -> {
219 PulseaudioBridgeHandler bridgeHandler = getPulseaudioBridgeHandler();
220 if (bridgeHandler != null) {
221 if (bridgeHandler.getDevice(name) == null) {
222 updateStatus(ThingStatus.OFFLINE);
223 this.bridgeHandler = null;
225 updateStatus(ThingStatus.ONLINE);
228 logger.debug("Bridge for pulseaudio device {} not found.", name);
229 updateStatus(ThingStatus.OFFLINE);
231 } catch (Exception e) {
232 logger.debug("Exception occurred during execution: {}", e.getMessage(), e);
233 this.bridgeHandler = null;
237 refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, refresh, TimeUnit.SECONDS);
240 private synchronized @Nullable PulseaudioBridgeHandler getPulseaudioBridgeHandler() {
241 if (this.bridgeHandler == null) {
242 Bridge bridge = getBridge();
243 if (bridge == null) {
244 logger.debug("Required bridge not defined for device {}.", name);
247 ThingHandler handler = bridge.getHandler();
248 if (handler instanceof PulseaudioBridgeHandler) {
249 this.bridgeHandler = (PulseaudioBridgeHandler) handler;
250 this.bridgeHandler.registerDeviceStatusListener(this);
252 logger.debug("No available bridge handler found for device {} bridge {} .", name, bridge.getUID());
256 return this.bridgeHandler;
260 public void handleCommand(ChannelUID channelUID, Command command) {
261 PulseaudioBridgeHandler bridge = getPulseaudioBridgeHandler();
262 if (bridge == null) {
263 logger.warn("pulseaudio server bridge handler not found. Cannot handle command without bridge.");
266 if (command instanceof RefreshType) {
267 bridge.handleCommand(channelUID, command);
271 AbstractAudioDeviceConfig device = bridge.getDevice(name);
272 if (device == null) {
273 logger.warn("device {} not found", name);
274 updateStatus(ThingStatus.OFFLINE);
275 bridgeHandler = null;
278 State updateState = UnDefType.UNDEF;
279 if (channelUID.getId().equals(VOLUME_CHANNEL)) {
280 if (command instanceof IncreaseDecreaseType) {
281 // refresh to get the current volume level
282 bridge.getClient().update();
283 device = bridge.getDevice(name);
284 int oldVolume = device.getVolume();
285 int newVolume = oldVolume;
286 if (command.equals(IncreaseDecreaseType.INCREASE)) {
287 newVolume = Math.min(100, oldVolume + 5);
289 if (command.equals(IncreaseDecreaseType.DECREASE)) {
290 newVolume = Math.max(0, oldVolume - 5);
292 bridge.getClient().setVolumePercent(device, newVolume);
293 updateState = new PercentType(newVolume);
294 savedVolume = newVolume;
295 } else if (command instanceof PercentType) {
296 DecimalType volume = (DecimalType) command;
297 bridge.getClient().setVolumePercent(device, volume.intValue());
298 updateState = (PercentType) command;
299 savedVolume = volume.intValue();
300 } else if (command instanceof DecimalType) {
302 DecimalType volume = (DecimalType) command;
303 bridge.getClient().setVolume(device, volume.intValue());
304 updateState = (DecimalType) command;
305 savedVolume = volume.intValue();
307 } else if (channelUID.getId().equals(MUTE_CHANNEL)) {
308 if (command instanceof OnOffType) {
309 bridge.getClient().setMute(device, OnOffType.ON.equals(command));
310 updateState = (OnOffType) command;
312 } else if (channelUID.getId().equals(SLAVES_CHANNEL)) {
313 if (device instanceof Sink && ((Sink) device).isCombinedSink()) {
314 if (command instanceof StringType) {
315 List<Sink> slaves = new ArrayList<>();
316 for (String slaveName : command.toString().split(",")) {
317 Sink slave = bridge.getClient().getSink(slaveName.trim());
322 if (!slaves.isEmpty()) {
323 bridge.getClient().setCombinedSinkSlaves(((Sink) device), slaves);
327 logger.error("{} is no combined sink", device);
329 } else if (channelUID.getId().equals(ROUTE_TO_SINK_CHANNEL)) {
330 if (device instanceof SinkInput) {
332 if (command instanceof DecimalType) {
333 newSink = bridge.getClient().getSink(((DecimalType) command).intValue());
335 newSink = bridge.getClient().getSink(command.toString());
337 if (newSink != null) {
338 logger.debug("rerouting {} to {}", device, newSink);
339 bridge.getClient().moveSinkInput(((SinkInput) device), newSink);
340 updateState = new StringType(newSink.getPaName());
342 logger.error("no sink {} found", command.toString());
346 logger.trace("updating {} to {}", channelUID, updateState);
347 if (!updateState.equals(UnDefType.UNDEF)) {
348 updateState(channelUID, updateState);
354 * Use last checked volume for faster access
358 public int getLastVolume() {
359 if (savedVolume == null) {
360 PulseaudioBridgeHandler bridge = getPulseaudioBridgeHandler();
361 AbstractAudioDeviceConfig device = bridge.getDevice(name);
362 // refresh to get the current volume level
363 bridge.getClient().update();
364 device = bridge.getDevice(name);
365 savedVolume = device.getVolume();
367 return savedVolume == null ? 50 : savedVolume;
370 public void setVolume(int volume) {
371 PulseaudioBridgeHandler bridge = getPulseaudioBridgeHandler();
372 AbstractAudioDeviceConfig device = bridge.getDevice(name);
373 bridge.getClient().setVolumePercent(device, volume);
374 updateState(VOLUME_CHANNEL, new PercentType(volume));
375 savedVolume = volume;
379 public void onDeviceStateChanged(ThingUID bridge, AbstractAudioDeviceConfig device) {
380 if (device.getPaName().equals(name)) {
381 updateStatus(ThingStatus.ONLINE);
382 logger.debug("Updating states of {} id: {}", device, VOLUME_CHANNEL);
383 savedVolume = device.getVolume();
384 updateState(VOLUME_CHANNEL, new PercentType(savedVolume));
385 updateState(MUTE_CHANNEL, device.isMuted() ? OnOffType.ON : OnOffType.OFF);
386 updateState(STATE_CHANNEL,
387 device.getState() != null ? new StringType(device.getState().toString()) : new StringType("-"));
388 if (device instanceof SinkInput) {
389 updateState(ROUTE_TO_SINK_CHANNEL,
390 ((SinkInput) device).getSink() != null
391 ? new StringType(((SinkInput) device).getSink().getPaName())
392 : new StringType("-"));
394 if (device instanceof Sink && ((Sink) device).isCombinedSink()) {
395 updateState(SLAVES_CHANNEL, new StringType(String.join(",", ((Sink) device).getCombinedSinkNames())));
400 public String getHost() {
401 Bridge bridge = getBridge();
402 if (bridge != null) {
403 return (String) bridge.getConfiguration().get(PulseaudioBindingConstants.BRIDGE_PARAMETER_HOST);
405 logger.error("A bridge must be configured for this pulseaudio thing");
411 * This method will scan the pulseaudio server to find the port on which the module/sink is listening
412 * If no module is listening, then it will command the module to load on the pulse audio server,
414 * @return the port on which the pulseaudio server is listening for this sink
415 * @throws InterruptedException when interrupted during the loading module wait
417 public int getSimpleTcpPort() throws InterruptedException {
418 var bridgeHandler = getPulseaudioBridgeHandler();
419 AbstractAudioDeviceConfig device = bridgeHandler.getDevice(name);
420 String simpleTcpPortPrefName = (device instanceof Source) ? DEVICE_PARAMETER_AUDIO_SOURCE_PORT
421 : DEVICE_PARAMETER_AUDIO_SINK_PORT;
422 BigDecimal simpleTcpPortPref = ((BigDecimal) getThing().getConfiguration().get(simpleTcpPortPrefName));
423 int simpleTcpPort = simpleTcpPortPref != null ? simpleTcpPortPref.intValue()
424 : MODULE_SIMPLE_PROTOCOL_TCP_DEFAULT_PORT;
425 String simpleFormat = ((String) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_FORMAT));
426 BigDecimal simpleRate = (BigDecimal) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_RATE);
427 BigDecimal simpleChannels = (BigDecimal) getThing().getConfiguration()
428 .get(DEVICE_PARAMETER_AUDIO_SOURCE_CHANNELS);
429 return getPulseaudioBridgeHandler().getClient()
430 .loadModuleSimpleProtocolTcpIfNeeded(device, simpleTcpPort, simpleFormat, simpleRate, simpleChannels)
431 .orElse(simpleTcpPort);
434 public @Nullable AudioFormat getSourceAudioFormat() {
435 String simpleFormat = ((String) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_FORMAT));
436 BigDecimal simpleRate = ((BigDecimal) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_RATE));
437 BigDecimal simpleChannels = ((BigDecimal) getThing().getConfiguration()
438 .get(DEVICE_PARAMETER_AUDIO_SOURCE_CHANNELS));
439 if (simpleFormat == null || simpleRate == null || simpleChannels == null) {
442 switch (simpleFormat) {
444 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, null, 8, 1,
445 simpleRate.longValue(), simpleChannels.intValue());
447 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, false, 16, 1,
448 simpleRate.longValue(), simpleChannels.intValue());
450 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, true, 16, 1,
451 simpleRate.longValue(), simpleChannels.intValue());
453 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_UNSIGNED, false, 24, 1,
454 simpleRate.longValue(), simpleChannels.intValue());
456 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_UNSIGNED, true, 24, 1,
457 simpleRate.longValue(), simpleChannels.intValue());
459 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_UNSIGNED, false, 32, 1,
460 simpleRate.longValue(), simpleChannels.intValue());
462 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_UNSIGNED, true, 32, 1,
463 simpleRate.longValue(), simpleChannels.intValue());
465 logger.warn("unsupported format {}", simpleFormat);
470 public int getIdleTimeout() {
471 var handler = getPulseaudioBridgeHandler();
472 if (handler == null) {
475 AbstractAudioDeviceConfig device = handler.getDevice(name);
476 String idleTimeoutPropName = (device instanceof Source) ? DEVICE_PARAMETER_AUDIO_SOURCE_IDLE_TIMEOUT
477 : DEVICE_PARAMETER_AUDIO_SINK_IDLE_TIMEOUT;
478 var idleTimeout = (BigDecimal) getThing().getConfiguration().get(idleTimeoutPropName);
479 return idleTimeout != null ? idleTimeout.intValue() : 30000;
482 public int getBasicProtocolSOTimeout() {
483 var soTimeout = (BigDecimal) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOCKET_SO_TIMEOUT);
484 return soTimeout != null ? soTimeout.intValue() : 500;
488 public void onDeviceRemoved(PulseaudioBridgeHandler bridge, AbstractAudioDeviceConfig device) {
489 if (device.getPaName().equals(name)) {
490 bridgeHandler.unregisterDeviceStatusListener(this);
491 bridgeHandler = null;
492 audioSink.disconnect();
494 updateStatus(ThingStatus.OFFLINE);
499 public void onDeviceAdded(Bridge bridge, AbstractAudioDeviceConfig device) {
500 logger.trace("new device discovered {} by {}", device, bridge);
503 public void setAudioSink(PulseAudioAudioSink audioSink) {
504 this.audioSink = audioSink;
507 public void setAudioSource(PulseAudioAudioSource audioSource) {
508 this.audioSource = audioSource;