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.Collections;
20 import java.util.HashSet;
21 import java.util.List;
23 import java.util.concurrent.CopyOnWriteArrayList;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
27 import org.openhab.binding.pulseaudio.internal.PulseAudioBindingConfiguration;
28 import org.openhab.binding.pulseaudio.internal.PulseAudioBindingConfigurationListener;
29 import org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants;
30 import org.openhab.binding.pulseaudio.internal.PulseaudioClient;
31 import org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig;
32 import org.openhab.core.config.core.Configuration;
33 import org.openhab.core.thing.Bridge;
34 import org.openhab.core.thing.ChannelUID;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.thing.binding.BaseBridgeHandler;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.RefreshType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * {@link PulseaudioBridgeHandler} is the handler for a Pulseaudio server and
45 * connects it to the framework.
47 * @author Tobias Bräutigam - Initial contribution
50 public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener {
51 private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
53 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
54 .singleton(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
56 public String host = "localhost";
57 public int port = 4712;
59 public int refreshInterval = 30000;
61 private PulseaudioClient client;
63 private PulseAudioBindingConfiguration configuration;
65 private List<DeviceStatusListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
66 private HashSet<String> lastActiveDevices = new HashSet<>();
68 private ScheduledFuture<?> pollingJob;
69 private Runnable pollingRunnable = () -> {
73 private synchronized void update() {
75 for (AbstractAudioDeviceConfig device : client.getItems()) {
76 if (lastActiveDevices != null && lastActiveDevices.contains(device.getPaName())) {
77 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
79 deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
80 } catch (Exception e) {
81 logger.error("An exception occurred while calling the DeviceStatusListener", e);
85 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
87 deviceStatusListener.onDeviceAdded(getThing(), device);
88 deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
89 } catch (Exception e) {
90 logger.error("An exception occurred while calling the DeviceStatusListener", e);
92 lastActiveDevices.add(device.getPaName());
98 public PulseaudioBridgeHandler(Bridge bridge, PulseAudioBindingConfiguration configuration) {
100 this.configuration = configuration;
104 public void handleCommand(ChannelUID channelUID, Command command) {
105 if (command instanceof RefreshType) {
108 logger.warn("received invalid command for pulseaudio bridge '{}'.", host);
112 private synchronized void startAutomaticRefresh() {
113 if (pollingJob == null || pollingJob.isCancelled()) {
114 pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, refreshInterval, TimeUnit.MILLISECONDS);
118 public AbstractAudioDeviceConfig getDevice(String name) {
119 return client.getGenericAudioItem(name);
122 public PulseaudioClient getClient() {
127 public void initialize() {
128 logger.debug("Initializing Pulseaudio handler.");
129 Configuration conf = this.getConfig();
131 if (conf.get(BRIDGE_PARAMETER_HOST) != null) {
132 this.host = String.valueOf(conf.get(BRIDGE_PARAMETER_HOST));
134 if (conf.get(BRIDGE_PARAMETER_PORT) != null) {
135 this.port = ((BigDecimal) conf.get(BRIDGE_PARAMETER_PORT)).intValue();
137 if (conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL) != null) {
138 this.refreshInterval = ((BigDecimal) conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL)).intValue();
141 if (host != null && !host.isEmpty()) {
142 Runnable connectRunnable = () -> {
144 client = new PulseaudioClient(host, port, configuration);
145 if (client.isConnected()) {
146 updateStatus(ThingStatus.ONLINE);
147 logger.info("Established connection to Pulseaudio server on Host '{}':'{}'.", host, port);
148 startAutomaticRefresh();
150 } catch (IOException e) {
151 logger.error("Couldn't connect to Pulsaudio server [Host '{}':'{}']: {}", host, port,
152 e.getLocalizedMessage());
153 updateStatus(ThingStatus.OFFLINE);
156 scheduler.schedule(connectRunnable, 0, TimeUnit.SECONDS);
159 "Couldn't connect to Pulseaudio server because of missing connection parameters [Host '{}':'{}'].",
161 updateStatus(ThingStatus.OFFLINE);
164 this.configuration.addPulseAudioBindingConfigurationListener(this);
168 public void dispose() {
169 this.configuration.removePulseAudioBindingConfigurationListener(this);
170 if (pollingJob != null) {
171 pollingJob.cancel(true);
173 if (client != null) {
179 public boolean registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
180 if (deviceStatusListener == null) {
181 throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
183 return deviceStatusListeners.add(deviceStatusListener);
186 public boolean unregisterDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
187 return deviceStatusListeners.remove(deviceStatusListener);
191 public void bindingConfigurationChanged() {