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.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);
77 apiClient = new EvohomeApiClient(configuration, this.httpClient);
79 // Initialization can take a while, so kick it off on a separate thread
80 scheduler.schedule(() -> {
81 if (apiClient.login()) {
82 if (checkInstallationInfoHasDuplicateIds(apiClient.getInstallationInfo())) {
85 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
86 "System Information Sanity Check failed");
89 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
90 "Authentication failed");
92 }, 0, TimeUnit.SECONDS);
97 public void dispose() {
104 public void handleCommand(ChannelUID channelUID, Command command) {
107 public Locations getEvohomeConfig() {
108 return apiClient.getInstallationInfo();
111 public LocationsStatus getEvohomeStatus() {
112 return apiClient.getInstallationStatus();
115 public void setTcsMode(String tcsId, String mode) {
116 tryToCall(() -> apiClient.setTcsMode(tcsId, mode));
119 public void setPermanentSetPoint(String zoneId, double doubleValue) {
120 tryToCall(() -> apiClient.setHeatingZoneOverride(zoneId, doubleValue));
123 public void cancelSetPointOverride(String zoneId) {
124 tryToCall(() -> apiClient.cancelHeatingZoneOverride(zoneId));
127 public void addAccountStatusListener(AccountStatusListener listener) {
128 listeners.add(listener);
129 listener.accountStatusChanged(getThing().getStatus());
132 public void removeAccountStatusListener(AccountStatusListener listener) {
133 listeners.remove(listener);
136 private void tryToCall(RunnableWithTimeout action) {
139 } catch (TimeoutException e) {
140 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
141 "Timeout on executing request");
145 private boolean checkInstallationInfoHasDuplicateIds(Locations locations) {
146 boolean result = true;
148 // Make sure that there are no duplicate IDs
149 Set<String> ids = new HashSet<>();
151 for (Location location : locations) {
152 result &= ids.add(location.getLocationInfo().getLocationId());
153 for (Gateway gateway : location.getGateways()) {
154 result &= ids.add(gateway.getGatewayInfo().getGatewayId());
155 for (TemperatureControlSystem tcs : gateway.getTemperatureControlSystems()) {
156 result &= ids.add(tcs.getSystemId());
157 for (Zone zone : tcs.getZones()) {
158 result &= ids.add(zone.getZoneId());
166 private void disposeApiClient() {
167 if (apiClient != null) {
173 private void disposeRefreshTask() {
174 if (refreshTask != null) {
175 refreshTask.cancel(true);
179 private boolean checkConfig() {
180 String errorMessage = "";
182 if (configuration == null) {
183 errorMessage = "Configuration is missing or corrupted";
184 } else if (configuration.username == null || configuration.username.isEmpty()) {
185 errorMessage = "Username not configured";
186 } else if (configuration.password == null || configuration.password.isEmpty()) {
187 errorMessage = "Password not configured";
192 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
196 private void startRefreshTask() {
197 disposeRefreshTask();
199 refreshTask = scheduler.scheduleWithFixedDelay(this::update, 0, configuration.refreshInterval,
203 private void update() {
206 updateAccountStatus(ThingStatus.ONLINE);
208 } catch (Exception e) {
209 updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
210 logger.debug("Failed to update installation status", e);
214 private void updateAccountStatus(ThingStatus newStatus) {
215 updateAccountStatus(newStatus, ThingStatusDetail.NONE, null);
218 private void updateAccountStatus(ThingStatus newStatus, ThingStatusDetail detail, String message) {
219 // Prevent spamming the log file
220 if (!newStatus.equals(getThing().getStatus())) {
221 updateStatus(newStatus, detail, message);
222 updateListeners(newStatus);
226 private void updateListeners(ThingStatus status) {
227 for (AccountStatusListener listener : listeners) {
228 listener.accountStatusChanged(status);
232 private void updateThings() {
233 Map<String, TemperatureControlSystemStatus> idToTcsMap = new HashMap<>();
234 Map<String, ZoneStatus> idToZoneMap = new HashMap<>();
235 Map<String, GatewayStatus> tcsIdToGatewayMap = new HashMap<>();
236 Map<String, String> zoneIdToTcsIdMap = new HashMap<>();
237 Map<String, ThingStatus> idToTcsThingsStatusMap = new HashMap<>();
239 // First, create a lookup table
240 for (LocationStatus location : apiClient.getInstallationStatus()) {
241 for (GatewayStatus gateway : location.getGateways()) {
242 for (TemperatureControlSystemStatus tcs : gateway.getTemperatureControlSystems()) {
243 idToTcsMap.put(tcs.getSystemId(), tcs);
244 tcsIdToGatewayMap.put(tcs.getSystemId(), gateway);
245 for (ZoneStatus zone : tcs.getZones()) {
246 idToZoneMap.put(zone.getZoneId(), zone);
247 zoneIdToTcsIdMap.put(zone.getZoneId(), tcs.getSystemId());
253 // Then update the things by type, with pre-filtered info
254 for (Thing handler : getThing().getThings()) {
255 ThingHandler thingHandler = handler.getHandler();
257 if (thingHandler instanceof EvohomeTemperatureControlSystemHandler) {
258 EvohomeTemperatureControlSystemHandler tcsHandler = (EvohomeTemperatureControlSystemHandler) thingHandler;
259 tcsHandler.update(tcsIdToGatewayMap.get(tcsHandler.getId()), idToTcsMap.get(tcsHandler.getId()));
260 idToTcsThingsStatusMap.put(tcsHandler.getId(), tcsHandler.getThing().getStatus());
262 if (thingHandler instanceof EvohomeHeatingZoneHandler) {
263 EvohomeHeatingZoneHandler zoneHandler = (EvohomeHeatingZoneHandler) thingHandler;
264 zoneHandler.update(idToTcsThingsStatusMap.get(zoneIdToTcsIdMap.get(zoneHandler.getId())),
265 idToZoneMap.get(zoneHandler.getId()));