]> git.basschouten.com Git - openhab-addons.git/blob
06e563f776ab477bfc6c5ec57fa8c6da2d585a50
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.evohome.internal.handler;
14
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.concurrent.CopyOnWriteArrayList;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24
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;
50
51 /**
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.
54  *
55  * @author Jasper van Zuijlen - Initial contribution
56  *
57  */
58 public class EvohomeAccountBridgeHandler extends BaseBridgeHandler {
59
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<>();
65
66     protected ScheduledFuture<?> refreshTask;
67
68     public EvohomeAccountBridgeHandler(Bridge thing, HttpClient httpClient) {
69         super(thing);
70         this.httpClient = httpClient;
71     }
72
73     @Override
74     public void initialize() {
75         configuration = getConfigAs(EvohomeAccountConfiguration.class);
76
77         if (checkConfig()) {
78             try {
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");
84             }
85
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())) {
91                             startRefreshTask();
92                         } else {
93                             updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
94                                     "System Information Sanity Check failed");
95                         }
96                     } else {
97                         updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
98                                 "Authentication failed");
99                     }
100                 }, 0, TimeUnit.SECONDS);
101             }
102         }
103     }
104
105     @Override
106     public void dispose() {
107         disposeRefreshTask();
108         disposeApiClient();
109         listeners.clear();
110     }
111
112     @Override
113     public void handleCommand(ChannelUID channelUID, Command command) {
114     }
115
116     public Locations getEvohomeConfig() {
117         return apiClient.getInstallationInfo();
118     }
119
120     public LocationsStatus getEvohomeStatus() {
121         return apiClient.getInstallationStatus();
122     }
123
124     public void setTcsMode(String tcsId, String mode) {
125         tryToCall(() -> apiClient.setTcsMode(tcsId, mode));
126     }
127
128     public void setPermanentSetPoint(String zoneId, double doubleValue) {
129         tryToCall(() -> apiClient.setHeatingZoneOverride(zoneId, doubleValue));
130     }
131
132     public void cancelSetPointOverride(String zoneId) {
133         tryToCall(() -> apiClient.cancelHeatingZoneOverride(zoneId));
134     }
135
136     public void addAccountStatusListener(AccountStatusListener listener) {
137         listeners.add(listener);
138         listener.accountStatusChanged(getThing().getStatus());
139     }
140
141     public void removeAccountStatusListener(AccountStatusListener listener) {
142         listeners.remove(listener);
143     }
144
145     private void tryToCall(RunnableWithTimeout action) {
146         try {
147             action.run();
148         } catch (TimeoutException e) {
149             updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
150                     "Timeout on executing request");
151         }
152     }
153
154     private boolean checkInstallationInfoHasDuplicateIds(Locations locations) {
155         boolean result = true;
156
157         // Make sure that there are no duplicate IDs
158         Set<String> ids = new HashSet<>();
159
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());
168                     }
169                 }
170             }
171         }
172         return result;
173     }
174
175     private void disposeApiClient() {
176         if (apiClient != null) {
177             apiClient.logout();
178         }
179         apiClient = null;
180     }
181
182     private void disposeRefreshTask() {
183         if (refreshTask != null) {
184             refreshTask.cancel(true);
185         }
186     }
187
188     private boolean checkConfig() {
189         String errorMessage = "";
190
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";
197         } else {
198             return true;
199         }
200
201         updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
202         return false;
203     }
204
205     private void startRefreshTask() {
206         disposeRefreshTask();
207
208         refreshTask = scheduler.scheduleWithFixedDelay(this::update, 0, configuration.refreshInterval,
209                 TimeUnit.SECONDS);
210     }
211
212     private void update() {
213         try {
214             apiClient.update();
215             updateAccountStatus(ThingStatus.ONLINE);
216             updateThings();
217         } catch (Exception e) {
218             updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
219             logger.debug("Failed to update installation status", e);
220         }
221     }
222
223     private void updateAccountStatus(ThingStatus newStatus) {
224         updateAccountStatus(newStatus, ThingStatusDetail.NONE, null);
225     }
226
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);
232         }
233     }
234
235     private void updateListeners(ThingStatus status) {
236         for (AccountStatusListener listener : listeners) {
237             listener.accountStatusChanged(status);
238         }
239     }
240
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<>();
247
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());
257                     }
258                 }
259             }
260         }
261
262         // Then update the things by type, with pre-filtered info
263         for (Thing handler : getThing().getThings()) {
264             ThingHandler thingHandler = handler.getHandler();
265
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());
270             }
271             if (thingHandler instanceof EvohomeHeatingZoneHandler) {
272                 EvohomeHeatingZoneHandler zoneHandler = (EvohomeHeatingZoneHandler) thingHandler;
273                 zoneHandler.update(idToTcsThingsStatusMap.get(zoneIdToTcsIdMap.get(zoneHandler.getId())),
274                         idToZoneMap.get(zoneHandler.getId()));
275             }
276         }
277     }
278 }