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