]> git.basschouten.com Git - openhab-addons.git/blob
eb5576dedc4e279472f18788a7930653bba30d17
[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.spotify.internal.discovery;
14
15 import static org.openhab.binding.spotify.internal.SpotifyBindingConstants.PROPERTY_SPOTIFY_DEVICE_NAME;
16 import static org.openhab.binding.spotify.internal.SpotifyBindingConstants.THING_TYPE_DEVICE;
17
18 import java.time.Duration;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Set;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.spotify.internal.SpotifyAccountHandler;
28 import org.openhab.binding.spotify.internal.SpotifyBindingConstants;
29 import org.openhab.binding.spotify.internal.api.model.Device;
30 import org.openhab.core.config.discovery.AbstractDiscoveryService;
31 import org.openhab.core.config.discovery.DiscoveryResult;
32 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
33 import org.openhab.core.config.discovery.DiscoveryService;
34 import org.openhab.core.thing.ThingTypeUID;
35 import org.openhab.core.thing.ThingUID;
36 import org.openhab.core.thing.binding.ThingHandler;
37 import org.openhab.core.thing.binding.ThingHandlerService;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * The {@link SpotifyDeviceDiscoveryService} queries the Spotify Web API for available devices.
43  *
44  * @author Andreas Stenlund - Initial contribution
45  * @author Hilbrand Bouwkamp - Simplfied code to make call to shared code
46  */
47 @NonNullByDefault
48 public class SpotifyDeviceDiscoveryService extends AbstractDiscoveryService
49         implements DiscoveryService, ThingHandlerService {
50
51     // id for device is derived by stripping id of device with this length
52     private static final int PLAYER_ID_LENGTH = 4;
53     // Only devices can be discovered. A bridge must be manually added.
54     private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_DEVICE);
55     // The call to listDevices is fast
56     private static final int DISCOVERY_TIME_SECONDS = 10;
57     // Check every minute for new devices
58     private static final long BACKGROUND_SCAN_REFRESH_MINUTES = 1;
59     // Time to life for discovered things.
60     private static final long TTL_SECONDS = Duration.ofHours(1).toSeconds();
61
62     private final Logger logger = LoggerFactory.getLogger(SpotifyDeviceDiscoveryService.class);
63
64     private @NonNullByDefault({}) SpotifyAccountHandler bridgeHandler;
65     private @NonNullByDefault({}) ThingUID bridgeUID;
66
67     private @Nullable ScheduledFuture<?> backgroundFuture;
68
69     public SpotifyDeviceDiscoveryService() {
70         super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS);
71     }
72
73     @Override
74     public Set<ThingTypeUID> getSupportedThingTypes() {
75         return SUPPORTED_THING_TYPES_UIDS;
76     }
77
78     @Override
79     public void activate() {
80         final Map<String, Object> properties = new HashMap<>();
81         properties.put(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, Boolean.TRUE);
82         super.activate(properties);
83     }
84
85     @Override
86     public void deactivate() {
87         super.deactivate();
88     }
89
90     @Override
91     public void setThingHandler(@Nullable ThingHandler handler) {
92         if (handler instanceof SpotifyAccountHandler accountHandler) {
93             bridgeHandler = accountHandler;
94             bridgeUID = bridgeHandler.getUID();
95         }
96     }
97
98     @Override
99     public @Nullable ThingHandler getThingHandler() {
100         return bridgeHandler;
101     }
102
103     @Override
104     protected synchronized void startBackgroundDiscovery() {
105         stopBackgroundDiscovery();
106         backgroundFuture = scheduler.scheduleWithFixedDelay(this::startScan, BACKGROUND_SCAN_REFRESH_MINUTES,
107                 BACKGROUND_SCAN_REFRESH_MINUTES, TimeUnit.MINUTES);
108     }
109
110     @Override
111     protected synchronized void stopBackgroundDiscovery() {
112         if (backgroundFuture != null) {
113             backgroundFuture.cancel(true);
114             backgroundFuture = null;
115         }
116     }
117
118     @Override
119     protected void startScan() {
120         // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment.
121         removeOlderResults(getTimestampOfLastScan());
122         if (bridgeHandler.isOnline()) {
123             logger.debug("Starting Spotify Device discovery for bridge {}", bridgeUID);
124             try {
125                 bridgeHandler.listDevices().forEach(this::thingDiscovered);
126             } catch (final RuntimeException e) {
127                 logger.debug("Finding devices failed with message: {}", e.getMessage(), e);
128             }
129         }
130     }
131
132     private void thingDiscovered(Device device) {
133         final Map<String, Object> properties = new HashMap<>();
134
135         properties.put(PROPERTY_SPOTIFY_DEVICE_NAME, device.getName());
136         final ThingUID thing = new ThingUID(SpotifyBindingConstants.THING_TYPE_DEVICE, bridgeUID,
137                 device.getId().substring(0, PLAYER_ID_LENGTH));
138
139         final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thing).withBridge(bridgeUID)
140                 .withProperties(properties).withRepresentationProperty(PROPERTY_SPOTIFY_DEVICE_NAME)
141                 .withTTL(TTL_SECONDS).withLabel(device.getName()).build();
142
143         thingDiscovered(discoveryResult);
144     }
145 }