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