]> git.basschouten.com Git - openhab-addons.git/blob
32136bbcc28db0d2048d517ef2c950ce47d9a0b0
[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.automower.internal.bridge;
14
15 import static org.openhab.binding.automower.internal.AutomowerBindingConstants.THING_TYPE_BRIDGE;
16
17 import java.util.Collections;
18 import java.util.Optional;
19 import java.util.Set;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.eclipse.jetty.client.HttpClient;
26 import org.openhab.binding.automower.internal.rest.api.automowerconnect.dto.MowerListResult;
27 import org.openhab.binding.automower.internal.rest.exceptions.AutomowerCommunicationException;
28 import org.openhab.core.auth.client.oauth2.OAuthClientService;
29 import org.openhab.core.auth.client.oauth2.OAuthFactory;
30 import org.openhab.core.thing.Bridge;
31 import org.openhab.core.thing.ChannelUID;
32 import org.openhab.core.thing.ThingStatus;
33 import org.openhab.core.thing.ThingStatusDetail;
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.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * The {@link AutomowerBridgeHandler} is responsible for handling commands, which are
42  * sent to one of the channels.
43  *
44  * @author Markus Pfleger - Initial contribution
45  */
46 @NonNullByDefault
47 public class AutomowerBridgeHandler extends BaseBridgeHandler {
48     private final Logger logger = LoggerFactory.getLogger(AutomowerBridgeHandler.class);
49
50     private static final String HUSQVARNA_API_TOKEN_URL = "https://api.authentication.husqvarnagroup.dev/v1/oauth2/token";
51
52     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
53     private static final long DEFAULT_POLLING_INTERVAL_S = TimeUnit.HOURS.toSeconds(1);
54
55     private final OAuthFactory oAuthFactory;
56
57     private @NonNullByDefault({}) OAuthClientService oAuthService;
58     private @Nullable ScheduledFuture<?> automowerBridgePollingJob;
59     private @Nullable AutomowerBridge bridge;
60     private final HttpClient httpClient;
61
62     public AutomowerBridgeHandler(Bridge bridge, OAuthFactory oAuthFactory, HttpClient httpClient) {
63         super(bridge);
64         this.oAuthFactory = oAuthFactory;
65         this.httpClient = httpClient;
66     }
67
68     private void pollAutomowers(AutomowerBridge bridge) {
69         MowerListResult automowers;
70         try {
71             automowers = bridge.getAutomowers();
72             updateStatus(ThingStatus.ONLINE);
73             logger.debug("Found {} automowers", automowers.getData().size());
74         } catch (AutomowerCommunicationException e) {
75             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
76                     "@text/comm-error-query-mowers-failed");
77             logger.warn("Unable to fetch automowers: {}", e.getMessage());
78         }
79     }
80
81     @Override
82     public void dispose() {
83         AutomowerBridge currentBridge = bridge;
84         if (currentBridge != null) {
85             stopAutomowerBridgePolling(currentBridge);
86             bridge = null;
87         }
88         oAuthFactory.ungetOAuthService(thing.getUID().getAsString());
89     }
90
91     @Override
92     public void initialize() {
93         AutomowerBridgeConfiguration bridgeConfiguration = getConfigAs(AutomowerBridgeConfiguration.class);
94
95         final String appKey = bridgeConfiguration.getAppKey();
96         final String userName = bridgeConfiguration.getUserName();
97         final String password = bridgeConfiguration.getPassword();
98         final Integer pollingIntervalS = bridgeConfiguration.getPollingInterval();
99
100         if (appKey == null || appKey.isEmpty()) {
101             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/conf-error-no-app-key");
102         } else if (userName == null || userName.isEmpty()) {
103             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/conf-error-no-username");
104         } else if (password == null || password.isEmpty()) {
105             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/conf-error-no-password");
106         } else if (pollingIntervalS != null && pollingIntervalS < 1) {
107             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
108                     "@text/conf-error-invalid-polling-interval");
109         } else {
110             oAuthService = oAuthFactory.createOAuthClientService(thing.getUID().getAsString(), HUSQVARNA_API_TOKEN_URL,
111                     null, appKey, null, null, null);
112
113             if (bridge == null) {
114                 AutomowerBridge currentBridge = new AutomowerBridge(oAuthService, appKey, userName, password,
115                         httpClient, scheduler);
116                 bridge = currentBridge;
117                 startAutomowerBridgePolling(currentBridge, pollingIntervalS);
118             }
119             updateStatus(ThingStatus.UNKNOWN);
120         }
121     }
122
123     private void startAutomowerBridgePolling(AutomowerBridge bridge, @Nullable Integer pollingIntervalS) {
124         ScheduledFuture<?> currentPollingJob = automowerBridgePollingJob;
125         if (currentPollingJob == null) {
126             final long pollingIntervalToUse = pollingIntervalS == null ? DEFAULT_POLLING_INTERVAL_S : pollingIntervalS;
127             automowerBridgePollingJob = scheduler.scheduleWithFixedDelay(() -> pollAutomowers(bridge), 1,
128                     pollingIntervalToUse, TimeUnit.SECONDS);
129         }
130     }
131
132     private void stopAutomowerBridgePolling(AutomowerBridge bridge) {
133         ScheduledFuture<?> currentPollingJob = automowerBridgePollingJob;
134         if (currentPollingJob != null) {
135             currentPollingJob.cancel(true);
136             automowerBridgePollingJob = null;
137         }
138     }
139
140     @Override
141     public void handleCommand(ChannelUID channelUID, Command command) {
142     }
143
144     public @Nullable AutomowerBridge getAutomowerBridge() {
145         return bridge;
146     }
147
148     public Optional<MowerListResult> getAutomowers() {
149         AutomowerBridge currentBridge = bridge;
150         if (currentBridge == null) {
151             return Optional.empty();
152         }
153
154         try {
155             return Optional.of(currentBridge.getAutomowers());
156         } catch (AutomowerCommunicationException e) {
157             logger.debug("Bridge cannot get list of available automowers {}", e.getMessage());
158             return Optional.empty();
159         }
160     }
161 }