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