]> git.basschouten.com Git - openhab-addons.git/blob
55360c17cfbf07e726b0c9b3a4d55db53c4d6a67
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.pulseaudio.internal.handler;
14
15 import static org.openhab.binding.pulseaudio.internal.PulseaudioBindingConstants.*;
16
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;
22 import java.util.Set;
23 import java.util.concurrent.CopyOnWriteArrayList;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26
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;
42
43 /**
44  * {@link PulseaudioBridgeHandler} is the handler for a Pulseaudio server and
45  * connects it to the framework.
46  *
47  * @author Tobias Bräutigam - Initial contribution
48  *
49  */
50 public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener {
51     private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
52
53     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
54             .singleton(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
55
56     public String host = "localhost";
57     public int port = 4712;
58
59     public int refreshInterval = 30000;
60
61     private PulseaudioClient client;
62
63     private PulseAudioBindingConfiguration configuration;
64
65     private List<DeviceStatusListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
66     private HashSet<String> lastActiveDevices = new HashSet<>();
67
68     private ScheduledFuture<?> pollingJob;
69     private Runnable pollingRunnable = () -> {
70         update();
71     };
72
73     private synchronized void update() {
74         client.update();
75         for (AbstractAudioDeviceConfig device : client.getItems()) {
76             if (lastActiveDevices != null && lastActiveDevices.contains(device.getPaName())) {
77                 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
78                     try {
79                         deviceStatusListener.onDeviceStateChanged(getThing().getUID(), device);
80                     } catch (Exception e) {
81                         logger.error("An exception occurred while calling the DeviceStatusListener", e);
82                     }
83                 }
84             } else {
85                 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
86                     try {
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);
91                     }
92                     lastActiveDevices.add(device.getPaName());
93                 }
94             }
95         }
96     }
97
98     public PulseaudioBridgeHandler(Bridge bridge, PulseAudioBindingConfiguration configuration) {
99         super(bridge);
100         this.configuration = configuration;
101     }
102
103     @Override
104     public void handleCommand(ChannelUID channelUID, Command command) {
105         if (command instanceof RefreshType) {
106             client.update();
107         } else {
108             logger.warn("received invalid command for pulseaudio bridge '{}'.", host);
109         }
110     }
111
112     private synchronized void startAutomaticRefresh() {
113         if (pollingJob == null || pollingJob.isCancelled()) {
114             pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, refreshInterval, TimeUnit.MILLISECONDS);
115         }
116     }
117
118     public AbstractAudioDeviceConfig getDevice(String name) {
119         return client.getGenericAudioItem(name);
120     }
121
122     public PulseaudioClient getClient() {
123         return client;
124     }
125
126     @Override
127     public void initialize() {
128         logger.debug("Initializing Pulseaudio handler.");
129         Configuration conf = this.getConfig();
130
131         if (conf.get(BRIDGE_PARAMETER_HOST) != null) {
132             this.host = String.valueOf(conf.get(BRIDGE_PARAMETER_HOST));
133         }
134         if (conf.get(BRIDGE_PARAMETER_PORT) != null) {
135             this.port = ((BigDecimal) conf.get(BRIDGE_PARAMETER_PORT)).intValue();
136         }
137         if (conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL) != null) {
138             this.refreshInterval = ((BigDecimal) conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL)).intValue();
139         }
140
141         if (host != null && !host.isEmpty()) {
142             Runnable connectRunnable = () -> {
143                 try {
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();
149                     }
150                 } catch (IOException e) {
151                     logger.error("Couldn't connect to Pulsaudio server [Host '{}':'{}']: {}", host, port,
152                             e.getLocalizedMessage());
153                     updateStatus(ThingStatus.OFFLINE);
154                 }
155             };
156             scheduler.schedule(connectRunnable, 0, TimeUnit.SECONDS);
157         } else {
158             logger.warn(
159                     "Couldn't connect to Pulseaudio server because of missing connection parameters [Host '{}':'{}'].",
160                     host, port);
161             updateStatus(ThingStatus.OFFLINE);
162         }
163
164         this.configuration.addPulseAudioBindingConfigurationListener(this);
165     }
166
167     @Override
168     public void dispose() {
169         this.configuration.removePulseAudioBindingConfigurationListener(this);
170         if (pollingJob != null) {
171             pollingJob.cancel(true);
172         }
173         if (client != null) {
174             client.disconnect();
175         }
176         super.dispose();
177     }
178
179     public boolean registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
180         if (deviceStatusListener == null) {
181             throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
182         }
183         return deviceStatusListeners.add(deviceStatusListener);
184     }
185
186     public boolean unregisterDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
187         return deviceStatusListeners.remove(deviceStatusListener);
188     }
189
190     @Override
191     public void bindingConfigurationChanged() {
192         update();
193     }
194 }