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.HashSet;
20 import java.util.List;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.pulseaudio.internal.PulseAudioBindingConfiguration;
29 import org.openhab.binding.pulseaudio.internal.PulseAudioBindingConfigurationListener;
30 import org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants;
31 import org.openhab.binding.pulseaudio.internal.PulseaudioClient;
32 import org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig;
33 import org.openhab.core.config.core.Configuration;
34 import org.openhab.core.thing.Bridge;
35 import org.openhab.core.thing.ChannelUID;
36 import org.openhab.core.thing.Thing;
37 import org.openhab.core.thing.ThingStatus;
38 import org.openhab.core.thing.ThingStatusDetail;
39 import org.openhab.core.thing.ThingTypeUID;
40 import org.openhab.core.thing.binding.BaseBridgeHandler;
41 import org.openhab.core.thing.binding.ThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * {@link PulseaudioBridgeHandler} is the handler for a Pulseaudio server and
49 * connects it to the framework.
51 * @author Tobias Bräutigam - Initial contribution
52 * @author Gwendal Roulleau - Rewrite for child handler notification
56 public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener {
57 private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
59 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
60 .of(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
62 public String host = "localhost";
63 public int port = 4712;
65 public int refreshInterval = 30000;
68 private PulseaudioClient client;
70 private PulseAudioBindingConfiguration configuration;
72 private List<DeviceStatusListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
73 private Set<String> lastActiveDevices = new HashSet<>();
76 private ScheduledFuture<?> pollingJob;
78 private Set<PulseaudioHandler> childHandlersInitialized = new HashSet<>();
80 public synchronized void update() {
82 getClient().connect();
83 } catch (IOException e) {
84 logger.debug("{}", e.getMessage(), e);
85 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
86 String.format("Couldn't connect to Pulsaudio server [Host '%s':'%d']: %s", host, port,
87 e.getMessage() != null ? e.getMessage() : ""));
92 if (getThing().getStatus() != ThingStatus.ONLINE) {
93 updateStatus(ThingStatus.ONLINE);
94 logger.debug("Established connection to Pulseaudio server on Host '{}':'{}'.", host, port);
95 // The framework will automatically notify the child handlers as the bridge status is changed
97 // browse all child handlers to update status according to the result of the query to the pulse audio server
98 for (PulseaudioHandler pulseaudioHandler : childHandlersInitialized) {
99 pulseaudioHandler.deviceUpdate(getDevice(pulseaudioHandler.getDeviceIdentifier()));
102 // browse query result to notify add event
103 for (AbstractAudioDeviceConfig device : getClient().getItems()) {
104 if (!lastActiveDevices.contains(device.getPaName())) {
105 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
107 deviceStatusListener.onDeviceAdded(getThing(), device);
108 } catch (Exception e) {
109 logger.warn("An exception occurred while calling the DeviceStatusListener", e);
111 lastActiveDevices.add(device.getPaName());
117 public PulseaudioBridgeHandler(Bridge bridge, PulseAudioBindingConfiguration configuration) {
119 this.configuration = configuration;
123 public void handleCommand(ChannelUID channelUID, Command command) {
124 if (command instanceof RefreshType) {
125 getClient().update();
127 logger.debug("received unexpected command for pulseaudio bridge '{}'.", host);
131 public @Nullable AbstractAudioDeviceConfig getDevice(@Nullable DeviceIdentifier deviceIdentifier) {
132 return deviceIdentifier == null ? null : getClient().getGenericAudioItem(deviceIdentifier);
135 public PulseaudioClient getClient() {
136 PulseaudioClient clientFinal = client;
137 if (clientFinal == null) {
138 throw new AssertionError("PulseaudioClient is null !");
144 public void initialize() {
145 logger.debug("Initializing Pulseaudio handler.");
146 Configuration conf = this.getConfig();
148 if (conf.get(BRIDGE_PARAMETER_HOST) != null) {
149 this.host = String.valueOf(conf.get(BRIDGE_PARAMETER_HOST));
151 if (conf.get(BRIDGE_PARAMETER_PORT) != null) {
152 this.port = ((BigDecimal) conf.get(BRIDGE_PARAMETER_PORT)).intValue();
154 if (conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL) != null) {
155 this.refreshInterval = ((BigDecimal) conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL)).intValue();
158 if (!host.isBlank()) {
159 client = new PulseaudioClient(host, port, configuration);
160 updateStatus(ThingStatus.UNKNOWN);
161 final ScheduledFuture<?> pollingJobFinal = pollingJob;
162 if (pollingJobFinal == null || pollingJobFinal.isCancelled()) {
163 pollingJob = scheduler.scheduleWithFixedDelay(this::update, 0, refreshInterval, TimeUnit.MILLISECONDS);
166 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format(
167 "Couldn't connect to Pulseaudio server because of missing connection parameters [Host '%s':'%d']",
171 this.configuration.addPulseAudioBindingConfigurationListener(this);
175 public void dispose() {
176 this.configuration.removePulseAudioBindingConfigurationListener(this);
177 ScheduledFuture<?> job = pollingJob;
182 var clientFinal = client;
183 if (clientFinal != null) {
184 clientFinal.disconnect();
189 public boolean registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
190 return deviceStatusListeners.add(deviceStatusListener);
193 public boolean unregisterDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
194 return deviceStatusListeners.remove(deviceStatusListener);
198 public void bindingConfigurationChanged() {
199 // If the bridge thing is not well setup, we do nothing
200 if (getThing().getStatus() != ThingStatus.OFFLINE
201 || getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR) {
206 public void resetKnownActiveDevices() {
207 // If the bridge thing is not well setup, we do nothing
208 if (getThing().getStatus() != ThingStatus.OFFLINE
209 || getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR) {
210 lastActiveDevices = new HashSet<>();
216 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
217 if (childHandler instanceof PulseaudioHandler pulsaudioHandler) {
218 this.childHandlersInitialized.add(pulsaudioHandler);
220 logger.error("This bridge can only support PulseaudioHandler child");
225 public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
226 this.childHandlersInitialized.remove(childHandler);