2 * Copyright (c) 2010-2020 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.PulseaudioBindingConstants;
28 import org.openhab.binding.pulseaudio.internal.PulseaudioClient;
29 import org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig;
30 import org.openhab.core.config.core.Configuration;
31 import org.openhab.core.thing.Bridge;
32 import org.openhab.core.thing.ChannelUID;
33 import org.openhab.core.thing.ThingStatus;
34 import org.openhab.core.thing.ThingTypeUID;
35 import org.openhab.core.thing.binding.BaseBridgeHandler;
36 import org.openhab.core.types.Command;
37 import org.openhab.core.types.RefreshType;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * {@link PulseaudioBridgeHandler} is the handler for a Pulseaudio server and
43 * connects it to the framework.
45 * @author Tobias Bräutigam - Initial contribution
48 public class PulseaudioBridgeHandler extends BaseBridgeHandler {
49 private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
51 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
52 .singleton(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
54 public String host = "localhost";
55 public int port = 4712;
57 public int refreshInterval = 30000;
59 private PulseaudioClient client;
61 private List<DeviceStatusListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
62 private HashSet<String> lastActiveDevices = new HashSet<>();
64 private ScheduledFuture<?> pollingJob;
65 private Runnable pollingRunnable = () -> {
67 for (AbstractAudioDeviceConfig device : client.getItems()) {
68 if (lastActiveDevices != null && lastActiveDevices.contains(device.getPaName())) {
69 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
71 deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
72 } catch (Exception e) {
73 logger.error("An exception occurred while calling the DeviceStatusListener", e);
77 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
79 deviceStatusListener.onDeviceAdded(getThing(), device);
80 deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
81 } catch (Exception e) {
82 logger.error("An exception occurred while calling the DeviceStatusListener", e);
84 lastActiveDevices.add(device.getPaName());
90 public PulseaudioBridgeHandler(Bridge bridge) {
95 public void handleCommand(ChannelUID channelUID, Command command) {
96 if (command instanceof RefreshType) {
99 logger.warn("received invalid command for pulseaudio bridge '{}'.", host);
103 private synchronized void startAutomaticRefresh() {
104 if (pollingJob == null || pollingJob.isCancelled()) {
105 pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, refreshInterval, TimeUnit.MILLISECONDS);
109 public AbstractAudioDeviceConfig getDevice(String name) {
110 return client.getGenericAudioItem(name);
113 public PulseaudioClient getClient() {
118 public void initialize() {
119 logger.debug("Initializing Pulseaudio handler.");
120 Configuration conf = this.getConfig();
122 if (conf.get(BRIDGE_PARAMETER_HOST) != null) {
123 this.host = String.valueOf(conf.get(BRIDGE_PARAMETER_HOST));
125 if (conf.get(BRIDGE_PARAMETER_PORT) != null) {
126 this.port = ((BigDecimal) conf.get(BRIDGE_PARAMETER_PORT)).intValue();
128 if (conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL) != null) {
129 this.refreshInterval = ((BigDecimal) conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL)).intValue();
132 if (host != null && !host.isEmpty()) {
133 Runnable connectRunnable = () -> {
135 client = new PulseaudioClient(host, port);
136 if (client.isConnected()) {
137 updateStatus(ThingStatus.ONLINE);
138 logger.info("Established connection to Pulseaudio server on Host '{}':'{}'.", host, port);
139 startAutomaticRefresh();
141 } catch (IOException e) {
142 logger.error("Couldn't connect to Pulsaudio server [Host '{}':'{}']: {}", host, port,
143 e.getLocalizedMessage());
144 updateStatus(ThingStatus.OFFLINE);
147 scheduler.schedule(connectRunnable, 0, TimeUnit.SECONDS);
150 "Couldn't connect to Pulseaudio server because of missing connection parameters [Host '{}':'{}'].",
152 updateStatus(ThingStatus.OFFLINE);
157 public void dispose() {
158 pollingJob.cancel(true);
163 public boolean registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
164 if (deviceStatusListener == null) {
165 throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
167 return deviceStatusListeners.add(deviceStatusListener);
170 public boolean unregisterDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
171 return deviceStatusListeners.remove(deviceStatusListener);