2 * Copyright (c) 2010-2024 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.ecobee.internal.handler;
15 import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.CONFIG_THERMOSTAT_ID;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.CopyOnWriteArraySet;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicInteger;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.eclipse.jetty.client.HttpClient;
31 import org.openhab.binding.ecobee.internal.api.EcobeeApi;
32 import org.openhab.binding.ecobee.internal.config.EcobeeAccountConfiguration;
33 import org.openhab.binding.ecobee.internal.discovery.EcobeeDiscoveryService;
34 import org.openhab.binding.ecobee.internal.dto.SelectionDTO;
35 import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO;
36 import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatUpdateRequestDTO;
37 import org.openhab.binding.ecobee.internal.dto.thermostat.summary.SummaryResponseDTO;
38 import org.openhab.binding.ecobee.internal.function.FunctionRequest;
39 import org.openhab.core.auth.client.oauth2.OAuthFactory;
40 import org.openhab.core.thing.Bridge;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.thing.Thing;
43 import org.openhab.core.thing.ThingStatus;
44 import org.openhab.core.thing.ThingStatusDetail;
45 import org.openhab.core.thing.binding.BaseBridgeHandler;
46 import org.openhab.core.thing.binding.ThingHandler;
47 import org.openhab.core.thing.binding.ThingHandlerService;
48 import org.openhab.core.types.Command;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * The {@link EcobeeAccountBridgeHandler} is responsible for managing
54 * communication with the Ecobee API.
56 * @author Mark Hilbush - Initial contribution
59 public class EcobeeAccountBridgeHandler extends BaseBridgeHandler {
61 private static final int REFRESH_STARTUP_DELAY_SECONDS = 3;
62 private static final int REFRESH_INTERVAL_SECONDS = 1;
63 private static final int DEFAULT_REFRESH_INTERVAL_NORMAL_SECONDS = 20;
64 private static final int DEFAULT_REFRESH_INTERVAL_QUICK_SECONDS = 5;
65 private static final int DEFAULT_API_TIMEOUT_SECONDS = 20;
67 private final Logger logger = LoggerFactory.getLogger(EcobeeAccountBridgeHandler.class);
69 private final OAuthFactory oAuthFactory;
70 private final HttpClient httpClient;
72 private @NonNullByDefault({}) EcobeeApi api;
73 private @NonNullByDefault({}) String apiKey;
74 private int refreshIntervalNormal;
75 private int refreshIntervalQuick;
76 private int apiTimeout;
77 private boolean discoveryEnabled;
79 private final Map<String, EcobeeThermostatBridgeHandler> thermostatHandlers = new ConcurrentHashMap<>();
80 private final Set<String> thermostatIds = new CopyOnWriteArraySet<>();
82 private @Nullable Future<?> refreshThermostatsJob;
83 private final AtomicInteger refreshThermostatsCounter = new AtomicInteger(REFRESH_STARTUP_DELAY_SECONDS);
85 private @Nullable SummaryResponseDTO previousSummary;
87 public EcobeeAccountBridgeHandler(final Bridge bridge, OAuthFactory oAuthFactory, HttpClient httpClient) {
89 this.oAuthFactory = oAuthFactory;
90 this.httpClient = httpClient;
94 public void initialize() {
95 logger.debug("AccountBridge: Initializing");
97 EcobeeAccountConfiguration config = getConfigAs(EcobeeAccountConfiguration.class);
98 apiKey = config.apiKey;
101 value = config.refreshIntervalNormal;
102 refreshIntervalNormal = value == null ? DEFAULT_REFRESH_INTERVAL_NORMAL_SECONDS : value;
104 value = config.refreshIntervalQuick;
105 refreshIntervalQuick = value == null ? DEFAULT_REFRESH_INTERVAL_QUICK_SECONDS : value;
107 value = config.apiTimeout;
108 apiTimeout = (value == null ? DEFAULT_API_TIMEOUT_SECONDS : value) * 1000;
110 Boolean booleanValue = config.discoveryEnabled;
111 discoveryEnabled = booleanValue == null ? false : booleanValue.booleanValue();
112 logger.debug("AccountBridge: Thermostat and sensor discovery is {}", discoveryEnabled ? "enabled" : "disabled");
114 api = new EcobeeApi(this, apiKey, apiTimeout, oAuthFactory, httpClient);
116 scheduleRefreshJob();
117 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, "Checking authorization");
121 public void dispose() {
123 api.closeOAuthClientService();
124 logger.debug("AccountBridge: Disposing");
128 public void handleRemoval() {
129 oAuthFactory.deleteServiceAndAccessToken(thing.getUID().getAsString());
130 super.handleRemoval();
134 public void handleCommand(ChannelUID channelUID, Command command) {
138 public Collection<Class<? extends ThingHandlerService>> getServices() {
139 return Set.of(EcobeeDiscoveryService.class);
143 public void childHandlerInitialized(ThingHandler thermostatHandler, Thing thermostatThing) {
144 String thermostatId = (String) thermostatThing.getConfiguration().get(CONFIG_THERMOSTAT_ID);
145 thermostatHandlers.put(thermostatId, (EcobeeThermostatBridgeHandler) thermostatHandler);
146 thermostatIds.add(thermostatId);
148 logger.debug("AccountBridge: Adding thermostat handler for {} with id {}", thermostatThing.getUID(),
153 public void childHandlerDisposed(ThingHandler thermostatHandler, Thing thermostatThing) {
154 String thermostatId = (String) thermostatThing.getConfiguration().get(CONFIG_THERMOSTAT_ID);
155 thermostatHandlers.remove(thermostatId);
156 thermostatIds.remove(thermostatId);
157 logger.debug("AccountBridge: Removing thermostat handler for {} with id {}", thermostatThing.getUID(),
161 public boolean isBackgroundDiscoveryEnabled() {
162 return discoveryEnabled;
165 public void updateBridgeStatus(ThingStatus status) {
166 updateStatus(status);
169 public void updateBridgeStatus(ThingStatus status, ThingStatusDetail statusDetail, String statusMessage) {
170 updateStatus(status, statusDetail, statusMessage);
173 public boolean performThermostatFunction(FunctionRequest request) {
174 boolean success = api.performThermostatFunction(request);
181 public boolean performThermostatUpdate(ThermostatUpdateRequestDTO request) {
182 boolean success = api.performThermostatUpdate(request);
189 public SelectionDTO getSelection() {
190 SelectionDTO mergedSelection = new SelectionDTO();
191 for (EcobeeThermostatBridgeHandler handler : new ArrayList<>(thermostatHandlers.values())) {
192 SelectionDTO selection = handler.getSelection();
193 logger.trace("AccountBridge: Thermostat {} selection: {}", handler.getThing().getUID(), selection);
194 mergedSelection.mergeSelection(selection);
196 return mergedSelection;
199 public void markOnline() {
200 updateStatus(ThingStatus.ONLINE);
203 public List<ThermostatDTO> getRegisteredThermostats() {
204 return api.queryRegisteredThermostats();
208 * The refresh job updates the thermostat channels on the refresh interval set in the thermostat thing config.
209 * The thermostat update process involves first running a thermostat summary transaction to
210 * determine if any thermostat data has changed since the last summary. If any change is detected,
211 * a full query of the thermostats is performed.
213 private void refresh() {
214 refreshThermostats();
217 @SuppressWarnings("null")
218 private void refreshThermostats() {
219 if (refreshThermostatsCounter.getAndDecrement() == 0) {
220 refreshThermostatsCounter.set(refreshIntervalNormal);
221 SummaryResponseDTO summary = api.performThermostatSummaryQuery();
222 if (summary != null && summary.hasChanged(previousSummary) && !thermostatIds.isEmpty()) {
223 for (ThermostatDTO thermostat : api.performThermostatQuery(thermostatIds)) {
224 EcobeeThermostatBridgeHandler handler = thermostatHandlers.get(thermostat.identifier);
225 if (handler != null) {
226 handler.updateChannels(thermostat);
230 previousSummary = summary;
234 private void scheduleQuickPoll() {
235 if (refreshThermostatsCounter.get() > refreshIntervalQuick) {
236 logger.debug("AccountBridge: Scheduling quick poll");
237 refreshThermostatsCounter.set(refreshIntervalQuick);
242 private void scheduleRefreshJob() {
243 logger.debug("AccountBridge: Scheduling thermostat refresh job");
245 refreshThermostatsCounter.set(0);
246 refreshThermostatsJob = scheduler.scheduleWithFixedDelay(this::refresh, REFRESH_STARTUP_DELAY_SECONDS,
247 REFRESH_INTERVAL_SECONDS, TimeUnit.SECONDS);
250 private void cancelRefreshJob() {
251 Future<?> localRefreshThermostatsJob = refreshThermostatsJob;
252 if (localRefreshThermostatsJob != null) {
254 localRefreshThermostatsJob.cancel(true);
255 logger.debug("AccountBridge: Canceling thermostat refresh job");
259 private void forceFullNextPoll() {
260 previousSummary = null;