2 * Copyright (c) 2010-2023 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;
24 import java.util.Optional;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.regex.PatternSyntaxException;
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.audio.utils.AudioSinkUtils;
44 import org.openhab.core.config.core.Configuration;
45 import org.openhab.core.library.types.DecimalType;
46 import org.openhab.core.library.types.IncreaseDecreaseType;
47 import org.openhab.core.library.types.OnOffType;
48 import org.openhab.core.library.types.PercentType;
49 import org.openhab.core.library.types.StringType;
50 import org.openhab.core.thing.Bridge;
51 import org.openhab.core.thing.ChannelUID;
52 import org.openhab.core.thing.Thing;
53 import org.openhab.core.thing.ThingStatus;
54 import org.openhab.core.thing.ThingStatusDetail;
55 import org.openhab.core.thing.ThingStatusInfo;
56 import org.openhab.core.thing.ThingTypeUID;
57 import org.openhab.core.thing.binding.BaseThingHandler;
58 import org.openhab.core.thing.binding.ThingHandler;
59 import org.openhab.core.types.Command;
60 import org.openhab.core.types.RefreshType;
61 import org.openhab.core.types.State;
62 import org.openhab.core.types.UnDefType;
63 import org.osgi.framework.BundleContext;
64 import org.osgi.framework.ServiceRegistration;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
69 * The {@link PulseaudioHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * @author Tobias Bräutigam - Initial contribution
73 * @author Miguel Álvarez - Register audio source and refactor
76 public class PulseaudioHandler extends BaseThingHandler {
78 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
79 .unmodifiableSet(Stream.of(SINK_THING_TYPE, COMBINED_SINK_THING_TYPE, SINK_INPUT_THING_TYPE,
80 SOURCE_THING_TYPE, SOURCE_OUTPUT_THING_TYPE).collect(Collectors.toSet()));
81 private final Logger logger = LoggerFactory.getLogger(PulseaudioHandler.class);
83 private @Nullable DeviceIdentifier deviceIdentifier;
84 private @Nullable PulseAudioAudioSink audioSink;
85 private @Nullable PulseAudioAudioSource audioSource;
86 private @Nullable Integer savedVolume;
88 private final Map<String, ServiceRegistration<AudioSink>> audioSinkRegistrations = new ConcurrentHashMap<>();
89 private final Map<String, ServiceRegistration<AudioSource>> audioSourceRegistrations = new ConcurrentHashMap<>();
91 private final BundleContext bundleContext;
93 private AudioSinkUtils audioSinkUtils;
95 public PulseaudioHandler(Thing thing, BundleContext bundleContext, AudioSinkUtils audioSinkUtils) {
97 this.bundleContext = bundleContext;
98 this.audioSinkUtils = audioSinkUtils;
102 public void initialize() {
103 Configuration config = getThing().getConfiguration();
105 deviceIdentifier = new DeviceIdentifier((String) config.get(DEVICE_PARAMETER_NAME_OR_DESCRIPTION),
106 (String) config.get(DEVICE_PARAMETER_ADDITIONAL_FILTERS));
107 } catch (PatternSyntaxException p) {
108 deviceIdentifier = null;
109 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
110 "Incorrect regular expression: " + (String) config.get(DEVICE_PARAMETER_ADDITIONAL_FILTERS));
113 initializeWithTheBridge();
116 public @Nullable DeviceIdentifier getDeviceIdentifier() {
117 return deviceIdentifier;
120 private void audioSinkSetup() {
121 if (audioSink != null) {
122 // Audio sink is already setup
125 if (!SINK_THING_TYPE.equals(thing.getThingTypeUID())) {
128 // check the property to see if it's enabled :
129 Boolean sinkActivated = (Boolean) thing.getConfiguration().get(DEVICE_PARAMETER_AUDIO_SINK_ACTIVATION);
130 if (sinkActivated == null || !sinkActivated.booleanValue()) {
133 final PulseaudioHandler thisHandler = this;
134 PulseAudioAudioSink audioSink = new PulseAudioAudioSink(thisHandler, scheduler, audioSinkUtils);
135 scheduler.submit(new Runnable() {
138 PulseaudioHandler.this.audioSink = audioSink;
140 audioSink.connectIfNeeded();
141 } catch (IOException e) {
142 logger.warn("pulseaudio binding cannot connect to the module-simple-protocol-tcp on {} ({})",
143 getHost(), e.getMessage());
144 } catch (InterruptedException i) {
145 logger.info("Interrupted during sink audio connection: {}", i.getMessage());
150 // Register the sink as an audio sink in openhab
151 logger.trace("Registering an audio sink for pulse audio sink thing {}", thing.getUID());
152 @SuppressWarnings("unchecked")
153 ServiceRegistration<AudioSink> reg = (ServiceRegistration<AudioSink>) bundleContext
154 .registerService(AudioSink.class.getName(), audioSink, new Hashtable<>());
155 audioSinkRegistrations.put(thing.getUID().toString(), reg);
158 private void audioSinkUnsetup() {
159 PulseAudioAudioSink sink = audioSink;
164 // Unregister the potential pulse audio sink's audio sink
165 ServiceRegistration<AudioSink> sinkReg = audioSinkRegistrations.remove(getThing().getUID().toString());
166 if (sinkReg != null) {
167 logger.trace("Unregistering the audio sync service for pulse audio sink thing {}", getThing().getUID());
168 sinkReg.unregister();
172 private void audioSourceSetup() {
173 if (audioSource != null) {
174 // Audio source is already setup
177 if (!SOURCE_THING_TYPE.equals(thing.getThingTypeUID())) {
180 // check the property to see if it's enabled :
181 Boolean sourceActivated = (Boolean) thing.getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_ACTIVATION);
182 if (sourceActivated == null || !sourceActivated.booleanValue()) {
185 final PulseaudioHandler thisHandler = this;
186 PulseAudioAudioSource audioSource = new PulseAudioAudioSource(thisHandler, scheduler);
187 scheduler.submit(new Runnable() {
190 PulseaudioHandler.this.audioSource = audioSource;
192 audioSource.connectIfNeeded();
193 } catch (IOException e) {
194 logger.warn("pulseaudio binding cannot connect to the module-simple-protocol-tcp on {} ({})",
195 getHost(), e.getMessage());
196 } catch (InterruptedException i) {
197 logger.info("Interrupted during source audio connection: {}", i.getMessage());
202 // Register the source as an audio source in openhab
203 logger.trace("Registering an audio source for pulse audio source thing {}", thing.getUID());
204 @SuppressWarnings("unchecked")
205 ServiceRegistration<AudioSource> reg = (ServiceRegistration<AudioSource>) bundleContext
206 .registerService(AudioSource.class.getName(), audioSource, new Hashtable<>());
207 audioSourceRegistrations.put(thing.getUID().toString(), reg);
210 private void audioSourceUnsetup() {
211 PulseAudioAudioSource source = audioSource;
212 if (source != null) {
216 // Unregister the potential pulse audio source's audio sources
217 ServiceRegistration<AudioSource> sourceReg = audioSourceRegistrations.remove(getThing().getUID().toString());
218 if (sourceReg != null) {
219 logger.trace("Unregistering the audio sync service for pulse audio source thing {}", getThing().getUID());
220 sourceReg.unregister();
225 public void dispose() {
226 logger.trace("Thing {} {} disposed.", getThing().getUID(), safeGetDeviceNameOrDescription());
229 audioSourceUnsetup();
233 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
234 initializeWithTheBridge();
237 private void initializeWithTheBridge() {
238 PulseaudioBridgeHandler pulseaudioBridgeHandler = getPulseaudioBridgeHandler();
239 if (pulseaudioBridgeHandler == null) {
240 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
241 } else if (pulseaudioBridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) {
242 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
244 deviceUpdate(pulseaudioBridgeHandler.getDevice(deviceIdentifier));
248 private synchronized @Nullable PulseaudioBridgeHandler getPulseaudioBridgeHandler() {
249 Bridge bridge = getBridge();
250 if (bridge == null) {
251 logger.debug("Required bridge not defined for device {}.", safeGetDeviceNameOrDescription());
254 ThingHandler handler = bridge.getHandler();
255 if (handler instanceof PulseaudioBridgeHandler) {
256 return (PulseaudioBridgeHandler) handler;
258 logger.debug("No available bridge handler found for device {} bridge {} .",
259 safeGetDeviceNameOrDescription(), bridge.getUID());
265 public void handleCommand(ChannelUID channelUID, Command command) {
266 PulseaudioBridgeHandler briHandler = getPulseaudioBridgeHandler();
267 if (briHandler == null) {
268 logger.debug("pulseaudio server bridge handler not found. Cannot handle command without bridge.");
271 if (command instanceof RefreshType) {
272 briHandler.handleCommand(channelUID, command);
276 AbstractAudioDeviceConfig device = briHandler.getDevice(deviceIdentifier);
277 if (device == null) {
278 logger.warn("device {} not found", safeGetDeviceNameOrDescription());
282 State updateState = UnDefType.UNDEF;
283 if (channelUID.getId().equals(VOLUME_CHANNEL)) {
284 if (command instanceof IncreaseDecreaseType) {
285 // refresh to get the current volume level
286 briHandler.getClient().update();
287 device = briHandler.getDevice(deviceIdentifier);
288 if (device == null) {
289 logger.warn("missing device info, aborting");
292 int oldVolume = device.getVolume();
293 int newVolume = oldVolume;
294 if (command.equals(IncreaseDecreaseType.INCREASE)) {
295 newVolume = Math.min(100, oldVolume + 5);
297 if (command.equals(IncreaseDecreaseType.DECREASE)) {
298 newVolume = Math.max(0, oldVolume - 5);
300 briHandler.getClient().setVolumePercent(device, newVolume);
301 updateState = new PercentType(newVolume);
302 savedVolume = newVolume;
303 } else if (command instanceof PercentType) {
304 DecimalType volume = (DecimalType) command;
305 briHandler.getClient().setVolumePercent(device, volume.intValue());
306 updateState = (PercentType) command;
307 savedVolume = volume.intValue();
308 } else if (command instanceof DecimalType) {
310 DecimalType volume = (DecimalType) command;
311 briHandler.getClient().setVolume(device, volume.intValue());
312 updateState = (DecimalType) command;
313 savedVolume = volume.intValue();
315 } else if (channelUID.getId().equals(MUTE_CHANNEL)) {
316 if (command instanceof OnOffType) {
317 briHandler.getClient().setMute(device, OnOffType.ON.equals(command));
318 updateState = (OnOffType) command;
320 } else if (channelUID.getId().equals(SLAVES_CHANNEL)) {
321 if (device instanceof Sink && ((Sink) device).isCombinedSink()) {
322 if (command instanceof StringType) {
323 List<Sink> slaves = new ArrayList<>();
324 for (String slaveName : command.toString().split(",")) {
325 Sink slave = briHandler.getClient().getSink(slaveName.trim());
330 if (!slaves.isEmpty()) {
331 briHandler.getClient().setCombinedSinkSlaves(((Sink) device), slaves);
335 logger.warn("{} is no combined sink", device);
337 } else if (channelUID.getId().equals(ROUTE_TO_SINK_CHANNEL)) {
338 if (device instanceof SinkInput) {
340 if (command instanceof DecimalType) {
341 newSink = briHandler.getClient().getSink(((DecimalType) command).intValue());
343 newSink = briHandler.getClient().getSink(command.toString());
345 if (newSink != null) {
346 logger.debug("rerouting {} to {}", device, newSink);
347 briHandler.getClient().moveSinkInput(((SinkInput) device), newSink);
348 updateState = new StringType(newSink.getPaName());
350 logger.warn("no sink {} found", command.toString());
354 logger.trace("updating {} to {}", channelUID, updateState);
355 if (!updateState.equals(UnDefType.UNDEF)) {
356 updateState(channelUID, updateState);
362 * Use last checked volume for faster access
366 public Integer getLastVolume() {
367 Integer savedVolumeFinal = savedVolume;
368 if (savedVolumeFinal == null) {
369 PulseaudioBridgeHandler briHandler = getPulseaudioBridgeHandler();
370 if (briHandler != null) {
371 // refresh to get the current volume level
372 briHandler.getClient().update();
373 AbstractAudioDeviceConfig device = briHandler.getDevice(deviceIdentifier);
374 if (device != null) {
375 savedVolume = savedVolumeFinal = device.getVolume();
379 return savedVolumeFinal == null ? 50 : savedVolumeFinal;
382 public void setVolume(int volume) {
383 PulseaudioBridgeHandler briHandler = getPulseaudioBridgeHandler();
384 if (briHandler == null) {
385 logger.warn("bridge is not ready");
388 AbstractAudioDeviceConfig device = briHandler.getDevice(deviceIdentifier);
389 if (device == null) {
390 logger.warn("missing device info, aborting");
393 briHandler.getClient().setVolumePercent(device, volume);
394 updateState(VOLUME_CHANNEL, new PercentType(volume));
395 savedVolume = volume;
398 public void deviceUpdate(@Nullable AbstractAudioDeviceConfig device) {
399 if (device != null) {
400 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
401 logger.debug("Updating states of {} id: {}", device, VOLUME_CHANNEL);
402 int actualVolume = device.getVolume();
403 savedVolume = actualVolume;
404 updateState(VOLUME_CHANNEL, new PercentType(actualVolume));
405 updateState(MUTE_CHANNEL, OnOffType.from(device.isMuted()));
406 org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig.State state = device.getState();
407 updateState(STATE_CHANNEL, state != null ? new StringType(state.toString()) : new StringType("-"));
408 if (device instanceof SinkInput) {
409 updateState(ROUTE_TO_SINK_CHANNEL, new StringType(
410 Optional.ofNullable(((SinkInput) device).getSink()).map(Sink::getPaName).orElse("-")));
412 if (device instanceof Sink && ((Sink) device).isCombinedSink()) {
413 updateState(SLAVES_CHANNEL, new StringType(String.join(",", ((Sink) device).getCombinedSinkNames())));
418 updateState(VOLUME_CHANNEL, UnDefType.UNDEF);
419 updateState(MUTE_CHANNEL, UnDefType.UNDEF);
420 updateState(STATE_CHANNEL, UnDefType.UNDEF);
421 if (SINK_INPUT_THING_TYPE.equals(thing.getThingTypeUID())) {
422 updateState(ROUTE_TO_SINK_CHANNEL, UnDefType.UNDEF);
424 if (COMBINED_SINK_THING_TYPE.equals(thing.getThingTypeUID())) {
425 updateState(SLAVES_CHANNEL, UnDefType.UNDEF);
428 audioSourceUnsetup();
429 updateStatus(ThingStatus.OFFLINE);
433 public String getHost() {
434 Bridge bridge = getBridge();
435 if (bridge != null) {
436 return (String) bridge.getConfiguration().get(PulseaudioBindingConstants.BRIDGE_PARAMETER_HOST);
438 logger.warn("A bridge must be configured for this pulseaudio thing");
444 * This method will scan the pulseaudio server to find the port on which the module/sink/source is listening
445 * If no module is listening, then it will command the module to load on the pulse audio server,
447 * @return the port on which the pulseaudio server is listening for this sink/source
448 * @throws IOException when device info is not available
449 * @throws InterruptedException when interrupted during the loading module wait
451 public int getSimpleTcpPortAndLoadModuleIfNecessary() throws IOException, InterruptedException {
452 var briHandler = getPulseaudioBridgeHandler();
453 if (briHandler == null) {
454 throw new IOException("bridge is not ready");
456 AbstractAudioDeviceConfig device = briHandler.getDevice(deviceIdentifier);
457 if (device == null) {
458 throw new IOException(
459 "missing device info, device " + safeGetDeviceNameOrDescription() + " appears to be offline");
461 String simpleTcpPortPrefName = (device instanceof Source) ? DEVICE_PARAMETER_AUDIO_SOURCE_PORT
462 : DEVICE_PARAMETER_AUDIO_SINK_PORT;
463 BigDecimal simpleTcpPortPref = ((BigDecimal) getThing().getConfiguration().get(simpleTcpPortPrefName));
464 int simpleTcpPort = simpleTcpPortPref != null ? simpleTcpPortPref.intValue()
465 : MODULE_SIMPLE_PROTOCOL_TCP_DEFAULT_PORT;
466 String simpleFormat = ((String) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_FORMAT));
467 BigDecimal simpleRate = (BigDecimal) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_RATE);
468 BigDecimal simpleChannels = (BigDecimal) getThing().getConfiguration()
469 .get(DEVICE_PARAMETER_AUDIO_SOURCE_CHANNELS);
470 return briHandler.getClient()
471 .loadModuleSimpleProtocolTcpIfNeeded(device, simpleTcpPort, simpleFormat, simpleRate, simpleChannels)
472 .orElse(simpleTcpPort);
475 public @Nullable AudioFormat getSourceAudioFormat() {
476 String simpleFormat = ((String) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_FORMAT));
477 BigDecimal simpleRate = ((BigDecimal) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOURCE_RATE));
478 BigDecimal simpleChannels = ((BigDecimal) getThing().getConfiguration()
479 .get(DEVICE_PARAMETER_AUDIO_SOURCE_CHANNELS));
480 if (simpleFormat == null || simpleRate == null || simpleChannels == null) {
483 switch (simpleFormat) {
485 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_UNSIGNED, null, 8, 1,
486 simpleRate.longValue(), simpleChannels.intValue());
488 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, false, 16, 1,
489 simpleRate.longValue(), simpleChannels.intValue());
491 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, true, 16, 1,
492 simpleRate.longValue(), simpleChannels.intValue());
494 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, false, 24, 1,
495 simpleRate.longValue(), simpleChannels.intValue());
497 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, true, 24, 1,
498 simpleRate.longValue(), simpleChannels.intValue());
500 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, false, 32, 1,
501 simpleRate.longValue(), simpleChannels.intValue());
503 return new AudioFormat(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED, true, 32, 1,
504 simpleRate.longValue(), simpleChannels.intValue());
506 logger.warn("unsupported format {}", simpleFormat);
511 public int getIdleTimeout() {
512 var idleTimeout = 3000;
513 var handler = getPulseaudioBridgeHandler();
514 if (handler != null) {
515 AbstractAudioDeviceConfig device = handler.getDevice(deviceIdentifier);
516 String idleTimeoutPropName = (device instanceof Source) ? DEVICE_PARAMETER_AUDIO_SOURCE_IDLE_TIMEOUT
517 : DEVICE_PARAMETER_AUDIO_SINK_IDLE_TIMEOUT;
518 var idleTimeoutB = (BigDecimal) getThing().getConfiguration().get(idleTimeoutPropName);
519 if (idleTimeoutB != null) {
520 idleTimeout = idleTimeoutB.intValue();
526 private String safeGetDeviceNameOrDescription() {
527 DeviceIdentifier deviceIdentifierFinal = deviceIdentifier;
528 return deviceIdentifierFinal == null ? "UNKNOWN" : deviceIdentifierFinal.getNameOrDescription();
531 public int getBasicProtocolSOTimeout() {
532 var soTimeout = (BigDecimal) getThing().getConfiguration().get(DEVICE_PARAMETER_AUDIO_SOCKET_SO_TIMEOUT);
533 return soTimeout != null ? soTimeout.intValue() : 500;