]> git.basschouten.com Git - openhab-addons.git/blob
5b5d9f266aa412b175375d3b26463f36bb8a1440
[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.weatherunderground.internal.discovery;
14
15 import static org.openhab.binding.weatherunderground.internal.WeatherUndergroundBindingConstants.*;
16 import static org.openhab.binding.weatherunderground.internal.config.WeatherUndergroundConfiguration.*;
17
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.Locale;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.Set;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26
27 import org.openhab.binding.weatherunderground.internal.handler.WeatherUndergroundHandler;
28 import org.openhab.core.config.discovery.AbstractDiscoveryService;
29 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
30 import org.openhab.core.i18n.LocaleProvider;
31 import org.openhab.core.i18n.LocationProvider;
32 import org.openhab.core.library.types.PointType;
33 import org.openhab.core.thing.ThingTypeUID;
34 import org.openhab.core.thing.ThingUID;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * The {@link WeatherUndergroundDiscoveryService} creates things based on the configured location.
40  *
41  * @author Laurent Garnier - Initial Contribution
42  * @author Laurent Garnier - Consider locale (language) when discovering a new thing
43  */
44 public class WeatherUndergroundDiscoveryService extends AbstractDiscoveryService {
45
46     private final Logger logger = LoggerFactory.getLogger(WeatherUndergroundDiscoveryService.class);
47     private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_WEATHER);
48     private static final int DISCOVER_TIMEOUT_SECONDS = 2;
49     private static final int LOCATION_CHANGED_CHECK_INTERVAL = 60;
50
51     private final LocaleProvider localeProvider;
52     private final LocationProvider locationProvider;
53     private ScheduledFuture<?> discoveryJob;
54     private PointType previousLocation;
55     private String previousLanguage;
56     private String previousCountry;
57
58     private final ThingUID bridgeUID;
59
60     /**
61      * Creates a WeatherUndergroundDiscoveryService with enabled autostart.
62      */
63
64     public WeatherUndergroundDiscoveryService(ThingUID bridgeUID, LocaleProvider localeProvider,
65             LocationProvider locationProvider) {
66         super(SUPPORTED_THING_TYPES, DISCOVER_TIMEOUT_SECONDS, true);
67         this.bridgeUID = bridgeUID;
68         this.localeProvider = localeProvider;
69         this.locationProvider = locationProvider;
70     }
71
72     /* We override this method to allow a call from the thing handler factory */
73     @Override
74     public void activate(Map<String, Object> configProperties) {
75         super.activate(configProperties);
76     }
77
78     /* We override this method to allow a call from the thing handler factory */
79     @Override
80     public void deactivate() {
81         super.deactivate();
82     }
83
84     @Override
85     protected void startScan() {
86         logger.debug("Starting Weather Underground discovery scan");
87         PointType location = locationProvider.getLocation();
88         if (location == null) {
89             logger.debug("LocationProvider.getLocation() is not set -> Will not provide any discovery results");
90             return;
91         }
92         createResults(location, localeProvider.getLocale());
93     }
94
95     @Override
96     protected void startBackgroundDiscovery() {
97         logger.debug("Starting Weather Underground device background discovery");
98         if (discoveryJob == null || discoveryJob.isCancelled()) {
99             discoveryJob = scheduler.scheduleWithFixedDelay(() -> {
100                 PointType currentLocation = locationProvider.getLocation();
101                 String currentLanguage = localeProvider.getLocale().getLanguage();
102                 String currentCountry = localeProvider.getLocale().getCountry();
103                 if (currentLocation != null) {
104                     boolean update = false;
105                     if (!Objects.equals(currentLocation, previousLocation)) {
106                         logger.debug("Location has been changed from {} to {}: Creating new discovery result",
107                                 previousLocation, currentLocation);
108                         update = true;
109                     } else if (!Objects.equals(currentLanguage, previousLanguage)) {
110                         logger.debug("Language has been changed from {} to {}: Creating new discovery result",
111                                 previousLanguage, currentLanguage);
112                         update = true;
113                     } else if (!Objects.equals(currentCountry, previousCountry)) {
114                         logger.debug("Country has been changed from {} to {}: Creating new discovery result",
115                                 previousCountry, currentCountry);
116                         update = true;
117                     }
118                     if (update) {
119                         createResults(currentLocation, localeProvider.getLocale());
120                         previousLocation = currentLocation;
121                         previousLanguage = currentLanguage;
122                         previousCountry = currentCountry;
123                     }
124                 }
125             }, 0, LOCATION_CHANGED_CHECK_INTERVAL, TimeUnit.SECONDS);
126             logger.debug("Scheduled Weather Underground location-changed job every {} seconds",
127                     LOCATION_CHANGED_CHECK_INTERVAL);
128         }
129     }
130
131     @Override
132     protected void stopBackgroundDiscovery() {
133         logger.debug("Stopping Weather Underground device background discovery");
134         if (discoveryJob != null && !discoveryJob.isCancelled()) {
135             discoveryJob.cancel(true);
136             discoveryJob = null;
137             logger.debug("Stopped Weather Underground device background discovery");
138         }
139     }
140
141     private void createResults(PointType location, Locale locale) {
142         ThingUID localWeatherThing = new ThingUID(THING_TYPE_WEATHER, bridgeUID, LOCAL);
143         Map<String, Object> properties = new HashMap<>(3);
144         properties.put(LOCATION, String.format("%s,%s", location.getLatitude(), location.getLongitude()));
145         String lang = WeatherUndergroundHandler.getCodeFromLanguage(locale);
146         if (!lang.isEmpty()) {
147             properties.put(LANGUAGE, lang);
148         }
149         thingDiscovered(DiscoveryResultBuilder.create(localWeatherThing).withLabel("Local Weather")
150                 .withProperties(properties).withBridge(bridgeUID).build());
151     }
152 }