]> git.basschouten.com Git - openhab-addons.git/blob
e6a327505d7311665b909f6c60f68ca47673fbad
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.HashSet;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
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.Thing;
37 import org.openhab.core.thing.ThingStatus;
38 import org.openhab.core.thing.ThingStatusDetail;
39 import org.openhab.core.thing.ThingTypeUID;
40 import org.openhab.core.thing.binding.BaseBridgeHandler;
41 import org.openhab.core.thing.binding.ThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * {@link PulseaudioBridgeHandler} is the handler for a Pulseaudio server and
49  * connects it to the framework.
50  *
51  * @author Tobias Bräutigam - Initial contribution
52  * @author Gwendal Roulleau - Rewrite for child handler notification
53  *
54  */
55 @NonNullByDefault
56 public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener {
57     private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
58
59     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
60             .of(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
61
62     public String host = "localhost";
63     public int port = 4712;
64
65     public int refreshInterval = 30000;
66
67     @Nullable
68     private PulseaudioClient client;
69
70     private PulseAudioBindingConfiguration configuration;
71
72     private List<DeviceStatusListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
73     private Set<String> lastActiveDevices = new HashSet<>();
74
75     @Nullable
76     private ScheduledFuture<?> pollingJob;
77
78     private Set<PulseaudioHandler> childHandlersInitialized = new HashSet<>();
79
80     public synchronized void update() {
81         try {
82             getClient().connect();
83         } catch (IOException e) {
84             logger.debug("{}", e.getMessage(), e);
85             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
86                     String.format("Couldn't connect to Pulsaudio server [Host '%s':'%d']: %s", host, port,
87                             e.getMessage() != null ? e.getMessage() : ""));
88             return;
89         }
90
91         getClient().update();
92         if (getThing().getStatus() != ThingStatus.ONLINE) {
93             updateStatus(ThingStatus.ONLINE);
94             logger.debug("Established connection to Pulseaudio server on Host '{}':'{}'.", host, port);
95             // The framework will automatically notify the child handlers as the bridge status is changed
96         } else {
97             // browse all child handlers to update status according to the result of the query to the pulse audio server
98             for (PulseaudioHandler pulseaudioHandler : childHandlersInitialized) {
99                 pulseaudioHandler.deviceUpdate(getDevice(pulseaudioHandler.getDeviceIdentifier()));
100             }
101         }
102         // browse query result to notify add event
103         for (AbstractAudioDeviceConfig device : getClient().getItems()) {
104             if (!lastActiveDevices.contains(device.getPaName())) {
105                 for (DeviceStatusListener deviceStatusListener : deviceStatusListeners) {
106                     try {
107                         deviceStatusListener.onDeviceAdded(getThing(), device);
108                     } catch (Exception e) {
109                         logger.warn("An exception occurred while calling the DeviceStatusListener", e);
110                     }
111                     lastActiveDevices.add(device.getPaName());
112                 }
113             }
114         }
115     }
116
117     public PulseaudioBridgeHandler(Bridge bridge, PulseAudioBindingConfiguration configuration) {
118         super(bridge);
119         this.configuration = configuration;
120     }
121
122     @Override
123     public void handleCommand(ChannelUID channelUID, Command command) {
124         if (command instanceof RefreshType) {
125             getClient().update();
126         } else {
127             logger.debug("received unexpected command for pulseaudio bridge '{}'.", host);
128         }
129     }
130
131     public @Nullable AbstractAudioDeviceConfig getDevice(@Nullable DeviceIdentifier deviceIdentifier) {
132         return deviceIdentifier == null ? null : getClient().getGenericAudioItem(deviceIdentifier);
133     }
134
135     public PulseaudioClient getClient() {
136         PulseaudioClient clientFinal = client;
137         if (clientFinal == null) {
138             throw new AssertionError("PulseaudioClient is null !");
139         }
140         return clientFinal;
141     }
142
143     @Override
144     public void initialize() {
145         logger.debug("Initializing Pulseaudio handler.");
146         Configuration conf = this.getConfig();
147
148         if (conf.get(BRIDGE_PARAMETER_HOST) != null) {
149             this.host = String.valueOf(conf.get(BRIDGE_PARAMETER_HOST));
150         }
151         if (conf.get(BRIDGE_PARAMETER_PORT) != null) {
152             this.port = ((BigDecimal) conf.get(BRIDGE_PARAMETER_PORT)).intValue();
153         }
154         if (conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL) != null) {
155             this.refreshInterval = ((BigDecimal) conf.get(BRIDGE_PARAMETER_REFRESH_INTERVAL)).intValue();
156         }
157
158         if (!host.isBlank()) {
159             client = new PulseaudioClient(host, port, configuration);
160             updateStatus(ThingStatus.UNKNOWN);
161             final ScheduledFuture<?> pollingJobFinal = pollingJob;
162             if (pollingJobFinal == null || pollingJobFinal.isCancelled()) {
163                 pollingJob = scheduler.scheduleWithFixedDelay(this::update, 0, refreshInterval, TimeUnit.MILLISECONDS);
164             }
165         } else {
166             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format(
167                     "Couldn't connect to Pulseaudio server because of missing connection parameters [Host '%s':'%d']",
168                     host, port));
169         }
170
171         this.configuration.addPulseAudioBindingConfigurationListener(this);
172     }
173
174     @Override
175     public void dispose() {
176         this.configuration.removePulseAudioBindingConfigurationListener(this);
177         ScheduledFuture<?> job = pollingJob;
178         if (job != null) {
179             job.cancel(true);
180             pollingJob = null;
181         }
182         var clientFinal = client;
183         if (clientFinal != null) {
184             clientFinal.disconnect();
185         }
186         super.dispose();
187     }
188
189     public boolean registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
190         return deviceStatusListeners.add(deviceStatusListener);
191     }
192
193     public boolean unregisterDeviceStatusListener(DeviceStatusListener deviceStatusListener) {
194         return deviceStatusListeners.remove(deviceStatusListener);
195     }
196
197     @Override
198     public void bindingConfigurationChanged() {
199         // If the bridge thing is not well setup, we do nothing
200         if (getThing().getStatus() != ThingStatus.OFFLINE
201                 || getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR) {
202             update();
203         }
204     }
205
206     public void resetKnownActiveDevices() {
207         // If the bridge thing is not well setup, we do nothing
208         if (getThing().getStatus() != ThingStatus.OFFLINE
209                 || getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR) {
210             lastActiveDevices = new HashSet<>();
211             update();
212         }
213     }
214
215     @Override
216     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
217         if (childHandler instanceof PulseaudioHandler pulsaudioHandler) {
218             this.childHandlersInitialized.add(pulsaudioHandler);
219         } else {
220             logger.error("This bridge can only support PulseaudioHandler child");
221         }
222     }
223
224     @Override
225     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
226         this.childHandlersInitialized.remove(childHandler);
227     }
228 }