2 * Copyright (c) 2010-2021 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.evohome.internal.handler;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
20 import java.util.concurrent.CopyOnWriteArrayList;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
25 import org.eclipse.jetty.client.HttpClient;
26 import org.openhab.binding.evohome.internal.RunnableWithTimeout;
27 import org.openhab.binding.evohome.internal.api.EvohomeApiClient;
28 import org.openhab.binding.evohome.internal.api.models.v2.response.Gateway;
29 import org.openhab.binding.evohome.internal.api.models.v2.response.GatewayStatus;
30 import org.openhab.binding.evohome.internal.api.models.v2.response.Location;
31 import org.openhab.binding.evohome.internal.api.models.v2.response.LocationStatus;
32 import org.openhab.binding.evohome.internal.api.models.v2.response.Locations;
33 import org.openhab.binding.evohome.internal.api.models.v2.response.LocationsStatus;
34 import org.openhab.binding.evohome.internal.api.models.v2.response.TemperatureControlSystem;
35 import org.openhab.binding.evohome.internal.api.models.v2.response.TemperatureControlSystemStatus;
36 import org.openhab.binding.evohome.internal.api.models.v2.response.Zone;
37 import org.openhab.binding.evohome.internal.api.models.v2.response.ZoneStatus;
38 import org.openhab.binding.evohome.internal.configuration.EvohomeAccountConfiguration;
39 import org.openhab.core.thing.Bridge;
40 import org.openhab.core.thing.ChannelUID;
41 import org.openhab.core.thing.Thing;
42 import org.openhab.core.thing.ThingStatus;
43 import org.openhab.core.thing.ThingStatusDetail;
44 import org.openhab.core.thing.binding.BaseBridgeHandler;
45 import org.openhab.core.thing.binding.ThingHandler;
46 import org.openhab.core.types.Command;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * Provides the bridge for this binding. Controls the authentication sequence.
52 * Manages the scheduler for getting updates from the API and updates the Things it contains.
54 * @author Jasper van Zuijlen - Initial contribution
57 public class EvohomeAccountBridgeHandler extends BaseBridgeHandler {
59 private final Logger logger = LoggerFactory.getLogger(EvohomeAccountBridgeHandler.class);
60 private final HttpClient httpClient;
61 private EvohomeAccountConfiguration configuration;
62 private EvohomeApiClient apiClient;
63 private List<AccountStatusListener> listeners = new CopyOnWriteArrayList<>();
65 protected ScheduledFuture<?> refreshTask;
67 public EvohomeAccountBridgeHandler(Bridge thing, HttpClient httpClient) {
69 this.httpClient = httpClient;
73 public void initialize() {
74 configuration = getConfigAs(EvohomeAccountConfiguration.class);
78 apiClient = new EvohomeApiClient(configuration, this.httpClient);
79 } catch (Exception e) {
80 logger.error("Could not start API client", e);
81 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
82 "Could not create evohome API client");
85 if (apiClient != null) {
86 // Initialization can take a while, so kick it off on a separate thread
87 scheduler.schedule(() -> {
88 if (apiClient.login()) {
89 if (checkInstallationInfoHasDuplicateIds(apiClient.getInstallationInfo())) {
92 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
93 "System Information Sanity Check failed");
96 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
97 "Authentication failed");
99 }, 0, TimeUnit.SECONDS);
105 public void dispose() {
106 disposeRefreshTask();
112 public void handleCommand(ChannelUID channelUID, Command command) {
115 public Locations getEvohomeConfig() {
116 return apiClient.getInstallationInfo();
119 public LocationsStatus getEvohomeStatus() {
120 return apiClient.getInstallationStatus();
123 public void setTcsMode(String tcsId, String mode) {
124 tryToCall(() -> apiClient.setTcsMode(tcsId, mode));
127 public void setPermanentSetPoint(String zoneId, double doubleValue) {
128 tryToCall(() -> apiClient.setHeatingZoneOverride(zoneId, doubleValue));
131 public void cancelSetPointOverride(String zoneId) {
132 tryToCall(() -> apiClient.cancelHeatingZoneOverride(zoneId));
135 public void addAccountStatusListener(AccountStatusListener listener) {
136 listeners.add(listener);
137 listener.accountStatusChanged(getThing().getStatus());
140 public void removeAccountStatusListener(AccountStatusListener listener) {
141 listeners.remove(listener);
144 private void tryToCall(RunnableWithTimeout action) {
147 } catch (TimeoutException e) {
148 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
149 "Timeout on executing request");
153 private boolean checkInstallationInfoHasDuplicateIds(Locations locations) {
154 boolean result = true;
156 // Make sure that there are no duplicate IDs
157 Set<String> ids = new HashSet<>();
159 for (Location location : locations) {
160 result &= ids.add(location.getLocationInfo().getLocationId());
161 for (Gateway gateway : location.getGateways()) {
162 result &= ids.add(gateway.getGatewayInfo().getGatewayId());
163 for (TemperatureControlSystem tcs : gateway.getTemperatureControlSystems()) {
164 result &= ids.add(tcs.getSystemId());
165 for (Zone zone : tcs.getZones()) {
166 result &= ids.add(zone.getZoneId());
174 private void disposeApiClient() {
175 if (apiClient != null) {
181 private void disposeRefreshTask() {
182 if (refreshTask != null) {
183 refreshTask.cancel(true);
187 private boolean checkConfig() {
188 String errorMessage = "";
190 if (configuration == null) {
191 errorMessage = "Configuration is missing or corrupted";
192 } else if (configuration.username == null || configuration.username.isEmpty()) {
193 errorMessage = "Username not configured";
194 } else if (configuration.password == null || configuration.password.isEmpty()) {
195 errorMessage = "Password not configured";
200 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
204 private void startRefreshTask() {
205 disposeRefreshTask();
207 refreshTask = scheduler.scheduleWithFixedDelay(this::update, 0, configuration.refreshInterval,
211 private void update() {
214 updateAccountStatus(ThingStatus.ONLINE);
216 } catch (Exception e) {
217 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
218 logger.debug("Failed to update installation status", e);
222 private void updateAccountStatus(ThingStatus newStatus) {
223 updateAccountStatus(newStatus, ThingStatusDetail.NONE, null);
226 private void updateAccountStatus(ThingStatus newStatus, ThingStatusDetail detail, String message) {
227 // Prevent spamming the log file
228 if (!newStatus.equals(getThing().getStatus())) {
229 updateStatus(newStatus, detail, message);
230 updateListeners(newStatus);
234 private void updateListeners(ThingStatus status) {
235 for (AccountStatusListener listener : listeners) {
236 listener.accountStatusChanged(status);
240 private void updateThings() {
241 Map<String, TemperatureControlSystemStatus> idToTcsMap = new HashMap<>();
242 Map<String, ZoneStatus> idToZoneMap = new HashMap<>();
243 Map<String, GatewayStatus> tcsIdToGatewayMap = new HashMap<>();
244 Map<String, String> zoneIdToTcsIdMap = new HashMap<>();
245 Map<String, ThingStatus> idToTcsThingsStatusMap = new HashMap<>();
247 // First, create a lookup table
248 for (LocationStatus location : apiClient.getInstallationStatus()) {
249 for (GatewayStatus gateway : location.getGateways()) {
250 for (TemperatureControlSystemStatus tcs : gateway.getTemperatureControlSystems()) {
251 idToTcsMap.put(tcs.getSystemId(), tcs);
252 tcsIdToGatewayMap.put(tcs.getSystemId(), gateway);
253 for (ZoneStatus zone : tcs.getZones()) {
254 idToZoneMap.put(zone.getZoneId(), zone);
255 zoneIdToTcsIdMap.put(zone.getZoneId(), tcs.getSystemId());
261 // Then update the things by type, with pre-filtered info
262 for (Thing handler : getThing().getThings()) {
263 ThingHandler thingHandler = handler.getHandler();
265 if (thingHandler instanceof EvohomeTemperatureControlSystemHandler) {
266 EvohomeTemperatureControlSystemHandler tcsHandler = (EvohomeTemperatureControlSystemHandler) thingHandler;
267 tcsHandler.update(tcsIdToGatewayMap.get(tcsHandler.getId()), idToTcsMap.get(tcsHandler.getId()));
268 idToTcsThingsStatusMap.put(tcsHandler.getId(), tcsHandler.getThing().getStatus());
270 if (thingHandler instanceof EvohomeHeatingZoneHandler) {
271 EvohomeHeatingZoneHandler zoneHandler = (EvohomeHeatingZoneHandler) thingHandler;
272 zoneHandler.update(idToTcsThingsStatusMap.get(zoneIdToTcsIdMap.get(zoneHandler.getId())),
273 idToZoneMap.get(zoneHandler.getId()));