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.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.ThingStatus;
37 import org.openhab.core.thing.ThingTypeUID;
38 import org.openhab.core.thing.binding.BaseBridgeHandler;
39 import org.openhab.core.types.Command;
40 import org.openhab.core.types.RefreshType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * {@link PulseaudioBridgeHandler} is the handler for a Pulseaudio server and
46 * connects it to the framework.
48 * @author Tobias Bräutigam - Initial contribution
51 public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener {
52 private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
54 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
55 .singleton(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
57 public String host = "localhost";
58 public int port = 4712;
60 public int refreshInterval = 30000;
62 private PulseaudioClient client;
64 private PulseAudioBindingConfiguration configuration;
66 private List<DeviceStatusListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
67 private HashSet<String> lastActiveDevices = new HashSet<>();
69 private ScheduledFuture<?> pollingJob;
70 private Runnable pollingRunnable = () -> {
74 private synchronized void update() {
76 for (AbstractAudioDeviceConfig device : client.getItems()) {
77 if (lastActiveDevices != null && lastActiveDevices.contains(device.getPaName())) {
78 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
80 deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
81 } catch (Exception e) {
82 logger.error("An exception occurred while calling the DeviceStatusListener", e);
86 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
88 deviceStatusListener.onDeviceAdded(getThing(), device);
89 deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
90 } catch (Exception e) {
91 logger.error("An exception occurred while calling the DeviceStatusListener", e);
93 lastActiveDevices.add(device.getPaName());
99 public PulseaudioBridgeHandler(Bridge bridge, PulseAudioBindingConfiguration configuration) {
101 this.configuration = configuration;
105 public void handleCommand(ChannelUID channelUID, Command command) {
106 if (command instanceof RefreshType) {
109 logger.warn("received invalid command for pulseaudio bridge '{}'.", host);
113 private synchronized void startAutomaticRefresh() {
114 if (pollingJob == null || pollingJob.isCancelled()) {
115 pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, refreshInterval, TimeUnit.MILLISECONDS);
119 public @Nullable AbstractAudioDeviceConfig getDevice(String name) {
120 return client.getGenericAudioItem(name);
123 public PulseaudioClient getClient() {
128 public void initialize() {
129 logger.debug("Initializing Pulseaudio handler.");
130 Configuration conf = this.getConfig();
132 if (conf.get(BRIDGE_PARAMETER_HOST) != null) {
133 this.host = String.valueOf(conf.get(BRIDGE_PARAMETER_HOST));
135 if (conf.get(BRIDGE_PARAMETER_PORT) != null) {
136 this.port = ((BigDecimal) conf.get(BRIDGE_PARAMETER_PORT)).intValue();
138 if (conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL) != null) {
139 this.refreshInterval = ((BigDecimal) conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL)).intValue();
142 if (host != null && !host.isEmpty()) {
143 Runnable connectRunnable = () -> {
145 client = new PulseaudioClient(host, port, configuration);
146 if (client.isConnected()) {
147 updateStatus(ThingStatus.ONLINE);
148 logger.info("Established connection to Pulseaudio server on Host '{}':'{}'.", host, port);
149 startAutomaticRefresh();
151 } catch (IOException e) {
152 logger.error("Couldn't connect to Pulsaudio server [Host '{}':'{}']: {}", host, port,
153 e.getLocalizedMessage());
154 updateStatus(ThingStatus.OFFLINE);
157 scheduler.schedule(connectRunnable, 0, TimeUnit.SECONDS);
160 "Couldn't connect to Pulseaudio server because of missing connection parameters [Host '{}':'{}'].",
162 updateStatus(ThingStatus.OFFLINE);
165 this.configuration.addPulseAudioBindingConfigurationListener(this);
169 public void dispose() {
170 this.configuration.removePulseAudioBindingConfigurationListener(this);
171 if (pollingJob != null) {
172 pollingJob.cancel(true);
174 if (client != null) {
180 public boolean registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
181 if (deviceStatusListener == null) {
182 throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
184 return deviceStatusListeners.add(deviceStatusListener);
187 public boolean unregisterDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
188 return deviceStatusListeners.remove(deviceStatusListener);
192 public void bindingConfigurationChanged() {