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.apache.commons.lang.StringUtils;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.openhab.binding.evohome.internal.RunnableWithTimeout;
28 import org.openhab.binding.evohome.internal.api.EvohomeApiClient;
29 import org.openhab.binding.evohome.internal.api.models.v2.response.Gateway;
30 import org.openhab.binding.evohome.internal.api.models.v2.response.GatewayStatus;
31 import org.openhab.binding.evohome.internal.api.models.v2.response.Location;
32 import org.openhab.binding.evohome.internal.api.models.v2.response.LocationStatus;
33 import org.openhab.binding.evohome.internal.api.models.v2.response.Locations;
34 import org.openhab.binding.evohome.internal.api.models.v2.response.LocationsStatus;
35 import org.openhab.binding.evohome.internal.api.models.v2.response.TemperatureControlSystem;
36 import org.openhab.binding.evohome.internal.api.models.v2.response.TemperatureControlSystemStatus;
37 import org.openhab.binding.evohome.internal.api.models.v2.response.Zone;
38 import org.openhab.binding.evohome.internal.api.models.v2.response.ZoneStatus;
39 import org.openhab.binding.evohome.internal.configuration.EvohomeAccountConfiguration;
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.types.Command;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Provides the bridge for this binding. Controls the authentication sequence.
53 * Manages the scheduler for getting updates from the API and updates the Things it contains.
55 * @author Jasper van Zuijlen - Initial contribution
58 public class EvohomeAccountBridgeHandler extends BaseBridgeHandler {
60 private final Logger logger = LoggerFactory.getLogger(EvohomeAccountBridgeHandler.class);
61 private final HttpClient httpClient;
62 private EvohomeAccountConfiguration configuration;
63 private EvohomeApiClient apiClient;
64 private List<AccountStatusListener> listeners = new CopyOnWriteArrayList<>();
66 protected ScheduledFuture<?> refreshTask;
68 public EvohomeAccountBridgeHandler(Bridge thing, HttpClient httpClient) {
70 this.httpClient = httpClient;
74 public void initialize() {
75 configuration = getConfigAs(EvohomeAccountConfiguration.class);
79 apiClient = new EvohomeApiClient(configuration, this.httpClient);
80 } catch (Exception e) {
81 logger.error("Could not start API client", e);
82 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
83 "Could not create evohome API client");
86 if (apiClient != null) {
87 // Initialization can take a while, so kick it off on a separate thread
88 scheduler.schedule(() -> {
89 if (apiClient.login()) {
90 if (checkInstallationInfoHasDuplicateIds(apiClient.getInstallationInfo())) {
93 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
94 "System Information Sanity Check failed");
97 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
98 "Authentication failed");
100 }, 0, TimeUnit.SECONDS);
106 public void dispose() {
107 disposeRefreshTask();
113 public void handleCommand(ChannelUID channelUID, Command command) {
116 public Locations getEvohomeConfig() {
117 return apiClient.getInstallationInfo();
120 public LocationsStatus getEvohomeStatus() {
121 return apiClient.getInstallationStatus();
124 public void setTcsMode(String tcsId, String mode) {
125 tryToCall(() -> apiClient.setTcsMode(tcsId, mode));
128 public void setPermanentSetPoint(String zoneId, double doubleValue) {
129 tryToCall(() -> apiClient.setHeatingZoneOverride(zoneId, doubleValue));
132 public void cancelSetPointOverride(String zoneId) {
133 tryToCall(() -> apiClient.cancelHeatingZoneOverride(zoneId));
136 public void addAccountStatusListener(AccountStatusListener listener) {
137 listeners.add(listener);
138 listener.accountStatusChanged(getThing().getStatus());
141 public void removeAccountStatusListener(AccountStatusListener listener) {
142 listeners.remove(listener);
145 private void tryToCall(RunnableWithTimeout action) {
148 } catch (TimeoutException e) {
149 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
150 "Timeout on executing request");
154 private boolean checkInstallationInfoHasDuplicateIds(Locations locations) {
155 boolean result = true;
157 // Make sure that there are no duplicate IDs
158 Set<String> ids = new HashSet<>();
160 for (Location location : locations) {
161 result &= ids.add(location.getLocationInfo().getLocationId());
162 for (Gateway gateway : location.getGateways()) {
163 result &= ids.add(gateway.getGatewayInfo().getGatewayId());
164 for (TemperatureControlSystem tcs : gateway.getTemperatureControlSystems()) {
165 result &= ids.add(tcs.getSystemId());
166 for (Zone zone : tcs.getZones()) {
167 result &= ids.add(zone.getZoneId());
175 private void disposeApiClient() {
176 if (apiClient != null) {
182 private void disposeRefreshTask() {
183 if (refreshTask != null) {
184 refreshTask.cancel(true);
188 private boolean checkConfig() {
189 String errorMessage = "";
191 if (configuration == null) {
192 errorMessage = "Configuration is missing or corrupted";
193 } else if (StringUtils.isEmpty(configuration.username)) {
194 errorMessage = "Username not configured";
195 } else if (StringUtils.isEmpty(configuration.password)) {
196 errorMessage = "Password not configured";
201 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
205 private void startRefreshTask() {
206 disposeRefreshTask();
208 refreshTask = scheduler.scheduleWithFixedDelay(this::update, 0, configuration.refreshInterval,
212 private void update() {
215 updateAccountStatus(ThingStatus.ONLINE);
217 } catch (Exception e) {
218 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
219 logger.debug("Failed to update installation status", e);
223 private void updateAccountStatus(ThingStatus newStatus) {
224 updateAccountStatus(newStatus, ThingStatusDetail.NONE, null);
227 private void updateAccountStatus(ThingStatus newStatus, ThingStatusDetail detail, String message) {
228 // Prevent spamming the log file
229 if (!newStatus.equals(getThing().getStatus())) {
230 updateStatus(newStatus, detail, message);
231 updateListeners(newStatus);
235 private void updateListeners(ThingStatus status) {
236 for (AccountStatusListener listener : listeners) {
237 listener.accountStatusChanged(status);
241 private void updateThings() {
242 Map<String, TemperatureControlSystemStatus> idToTcsMap = new HashMap<>();
243 Map<String, ZoneStatus> idToZoneMap = new HashMap<>();
244 Map<String, GatewayStatus> tcsIdToGatewayMap = new HashMap<>();
245 Map<String, String> zoneIdToTcsIdMap = new HashMap<>();
246 Map<String, ThingStatus> idToTcsThingsStatusMap = new HashMap<>();
248 // First, create a lookup table
249 for (LocationStatus location : apiClient.getInstallationStatus()) {
250 for (GatewayStatus gateway : location.getGateways()) {
251 for (TemperatureControlSystemStatus tcs : gateway.getTemperatureControlSystems()) {
252 idToTcsMap.put(tcs.getSystemId(), tcs);
253 tcsIdToGatewayMap.put(tcs.getSystemId(), gateway);
254 for (ZoneStatus zone : tcs.getZones()) {
255 idToZoneMap.put(zone.getZoneId(), zone);
256 zoneIdToTcsIdMap.put(zone.getZoneId(), tcs.getSystemId());
262 // Then update the things by type, with pre-filtered info
263 for (Thing handler : getThing().getThings()) {
264 ThingHandler thingHandler = handler.getHandler();
266 if (thingHandler instanceof EvohomeTemperatureControlSystemHandler) {
267 EvohomeTemperatureControlSystemHandler tcsHandler = (EvohomeTemperatureControlSystemHandler) thingHandler;
268 tcsHandler.update(tcsIdToGatewayMap.get(tcsHandler.getId()), idToTcsMap.get(tcsHandler.getId()));
269 idToTcsThingsStatusMap.put(tcsHandler.getId(), tcsHandler.getThing().getStatus());
271 if (thingHandler instanceof EvohomeHeatingZoneHandler) {
272 EvohomeHeatingZoneHandler zoneHandler = (EvohomeHeatingZoneHandler) thingHandler;
273 zoneHandler.update(idToTcsThingsStatusMap.get(zoneIdToTcsIdMap.get(zoneHandler.getId())),
274 idToZoneMap.get(zoneHandler.getId()));