2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ecovacs.internal.handler;
15 import static org.openhab.binding.ecovacs.internal.EcovacsBindingConstants.*;
17 import java.util.Collection;
18 import java.util.Optional;
20 import java.util.UUID;
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;
44 * The {@link EcovacsApiHandler} is responsible for connecting to the Ecovacs cloud API account.
46 * @author Danny Baumann - Initial contribution
49 public class EcovacsApiHandler extends BaseBridgeHandler {
50 private final Logger logger = LoggerFactory.getLogger(EcovacsApiHandler.class);
51 private static final long RETRY_INTERVAL_SECONDS = 120;
53 private Optional<EcovacsDeviceDiscoveryService> discoveryService = Optional.empty();
54 private SchedulerTask loginTask;
55 private final HttpClient httpClient;
56 private final LocaleProvider localeProvider;
58 public EcovacsApiHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
60 this.httpClient = httpClient;
61 this.localeProvider = localeProvider;
62 this.loginTask = new SchedulerTask(scheduler, logger, "API Login", this::loginToApi);
65 public void setDiscoveryService(EcovacsDeviceDiscoveryService discoveryService) {
66 this.discoveryService = Optional.of(discoveryService);
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");
74 return createApi("-" + serial, country);
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);
87 updateStatus(ThingStatus.UNKNOWN);
92 public void dispose() {
94 discoveryService.ifPresent(ds -> ds.stopScan());
98 public Collection<Class<? extends ThingHandlerService>> getServices() {
99 return Set.of(EcovacsDeviceDiscoveryService.class);
103 public void handleCommand(ChannelUID channelUID, Command command) {
104 if (RefreshType.REFRESH == command) {
105 logger.debug("Refreshing Ecovacs API account '{}'", getThing().getUID().getId());
110 public void onLoginExpired() {
111 logger.debug("Ecovacs API login for account '{}' expired, logging in again", getThing().getUID().getId());
115 private void scheduleLogin(long delaySeconds) {
117 loginTask.schedule(delaySeconds);
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);
127 return EcovacsApi.create(httpClient, apiConfig);
130 private void loginToApi() {
132 String country = localeProvider.getLocale().getCountry();
133 if (country.isEmpty()) {
134 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
135 "@text/offline.config-error-no-country");
138 EcovacsApi api = createApi("", country);
139 api.loginAndGetAccessToken();
140 updateStatus(ThingStatus.ONLINE);
141 discoveryService.ifPresent(ds -> ds.startScanningWithApi(api));
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);