]> git.basschouten.com Git - openhab-addons.git/blob
70c26224ae72eb6d87d6232615350ad9fb701268
[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.ecovacs.internal.handler;
14
15 import static org.openhab.binding.ecovacs.internal.EcovacsBindingConstants.*;
16
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Optional;
20 import java.util.UUID;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jetty.client.HttpClient;
24 import org.openhab.binding.ecovacs.internal.api.EcovacsApi;
25 import org.openhab.binding.ecovacs.internal.api.EcovacsApiException;
26 import org.openhab.binding.ecovacs.internal.api.util.SchedulerTask;
27 import org.openhab.binding.ecovacs.internal.config.EcovacsApiConfiguration;
28 import org.openhab.binding.ecovacs.internal.discovery.EcovacsDeviceDiscoveryService;
29 import org.openhab.core.config.core.Configuration;
30 import org.openhab.core.i18n.ConfigurationException;
31 import org.openhab.core.i18n.LocaleProvider;
32 import org.openhab.core.thing.Bridge;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.ThingStatus;
35 import org.openhab.core.thing.ThingStatusDetail;
36 import org.openhab.core.thing.binding.BaseBridgeHandler;
37 import org.openhab.core.thing.binding.ThingHandlerService;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.RefreshType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * The {@link EcovacsApiHandler} is responsible for connecting to the Ecovacs cloud API account.
45  *
46  * @author Danny Baumann - Initial contribution
47  */
48 @NonNullByDefault
49 public class EcovacsApiHandler extends BaseBridgeHandler {
50     private final Logger logger = LoggerFactory.getLogger(EcovacsApiHandler.class);
51     private static final long RETRY_INTERVAL_SECONDS = 120;
52
53     private Optional<EcovacsDeviceDiscoveryService> discoveryService = Optional.empty();
54     private SchedulerTask loginTask;
55     private final HttpClient httpClient;
56     private final LocaleProvider localeProvider;
57
58     public EcovacsApiHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
59         super(bridge);
60         this.httpClient = httpClient;
61         this.localeProvider = localeProvider;
62         this.loginTask = new SchedulerTask(scheduler, logger, "API Login", this::loginToApi);
63     }
64
65     public void setDiscoveryService(EcovacsDeviceDiscoveryService discoveryService) {
66         this.discoveryService = Optional.of(discoveryService);
67     }
68
69     public EcovacsApi createApiForDevice(String serial) throws ConfigurationException {
70         String country = localeProvider.getLocale().getCountry();
71         if (country.isEmpty()) {
72             throw new ConfigurationException("@text/offline.config-error-no-country");
73         }
74         return createApi("-" + serial, country);
75     }
76
77     @Override
78     public void initialize() {
79         logger.debug("Initializing Ecovacs account '{}'", getThing().getUID().getId());
80         // The API expects us to provide a unique device ID during authentication, so generate one once
81         // and keep it in configuration afterwards
82         if (!getConfig().keySet().contains("installId")) {
83             Configuration newConfig = editConfiguration();
84             newConfig.put("installId", UUID.randomUUID().toString());
85             updateConfiguration(newConfig);
86         }
87         updateStatus(ThingStatus.UNKNOWN);
88         loginTask.submit();
89     }
90
91     @Override
92     public void dispose() {
93         super.dispose();
94         discoveryService.ifPresent(ds -> ds.stopScan());
95     }
96
97     @Override
98     public Collection<Class<? extends ThingHandlerService>> getServices() {
99         return Collections.singleton(EcovacsDeviceDiscoveryService.class);
100     }
101
102     @Override
103     public void handleCommand(ChannelUID channelUID, Command command) {
104         if (RefreshType.REFRESH == command) {
105             logger.debug("Refreshing Ecovacs API account '{}'", getThing().getUID().getId());
106             scheduleLogin(0);
107         }
108     }
109
110     public void onLoginExpired() {
111         logger.debug("Ecovacs API login for account '{}' expired, logging in again", getThing().getUID().getId());
112         scheduleLogin(0);
113     }
114
115     private void scheduleLogin(long delaySeconds) {
116         loginTask.cancel();
117         loginTask.schedule(delaySeconds);
118     }
119
120     private EcovacsApi createApi(String deviceIdSuffix, String country) {
121         EcovacsApiConfiguration config = getConfigAs(EcovacsApiConfiguration.class);
122         String deviceId = config.installId + deviceIdSuffix;
123         org.openhab.binding.ecovacs.internal.api.EcovacsApiConfiguration apiConfig = new org.openhab.binding.ecovacs.internal.api.EcovacsApiConfiguration(
124                 deviceId, config.email, config.password, config.continent, country, "EN", CLIENT_KEY, CLIENT_SECRET,
125                 AUTH_CLIENT_KEY, AUTH_CLIENT_SECRET);
126
127         return EcovacsApi.create(httpClient, apiConfig);
128     }
129
130     private void loginToApi() {
131         try {
132             String country = localeProvider.getLocale().getCountry();
133             if (country.isEmpty()) {
134                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
135                         "@text/offline.config-error-no-country");
136                 return;
137             }
138             EcovacsApi api = createApi("", country);
139             api.loginAndGetAccessToken();
140             updateStatus(ThingStatus.ONLINE);
141             discoveryService.ifPresent(ds -> ds.startScanningWithApi(api));
142
143             logger.debug("Ecovacs API initialized");
144         } catch (InterruptedException e) {
145             Thread.currentThread().interrupt();
146             updateStatus(ThingStatus.OFFLINE);
147         } catch (EcovacsApiException e) {
148             logger.debug("Ecovacs API login failed", e);
149             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
150             scheduleLogin(RETRY_INTERVAL_SECONDS);
151         }
152     }
153 }