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