]> git.basschouten.com Git - openhab-addons.git/blob
22054a4e2a58f6cf76b693aab7a84df48e6d6ce4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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             apiClient = new EvohomeApiClient(configuration, this.httpClient);
78
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())) {
83                         startRefreshTask();
84                     } else {
85                         updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
86                                 "System Information Sanity Check failed");
87                     }
88                 } else {
89                     updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
90                             "Authentication failed");
91                 }
92             }, 0, TimeUnit.SECONDS);
93         }
94     }
95
96     @Override
97     public void dispose() {
98         disposeRefreshTask();
99         disposeApiClient();
100         listeners.clear();
101     }
102
103     @Override
104     public void handleCommand(ChannelUID channelUID, Command command) {
105     }
106
107     public Locations getEvohomeConfig() {
108         return apiClient.getInstallationInfo();
109     }
110
111     public LocationsStatus getEvohomeStatus() {
112         return apiClient.getInstallationStatus();
113     }
114
115     public void setTcsMode(String tcsId, String mode) {
116         tryToCall(() -> apiClient.setTcsMode(tcsId, mode));
117     }
118
119     public void setPermanentSetPoint(String zoneId, double doubleValue) {
120         tryToCall(() -> apiClient.setHeatingZoneOverride(zoneId, doubleValue));
121     }
122
123     public void cancelSetPointOverride(String zoneId) {
124         tryToCall(() -> apiClient.cancelHeatingZoneOverride(zoneId));
125     }
126
127     public void addAccountStatusListener(AccountStatusListener listener) {
128         listeners.add(listener);
129         listener.accountStatusChanged(getThing().getStatus());
130     }
131
132     public void removeAccountStatusListener(AccountStatusListener listener) {
133         listeners.remove(listener);
134     }
135
136     private void tryToCall(RunnableWithTimeout action) {
137         try {
138             action.run();
139         } catch (TimeoutException e) {
140             updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
141                     "Timeout on executing request");
142         }
143     }
144
145     private boolean checkInstallationInfoHasDuplicateIds(Locations locations) {
146         boolean result = true;
147
148         // Make sure that there are no duplicate IDs
149         Set<String> ids = new HashSet<>();
150
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());
159                     }
160                 }
161             }
162         }
163         return result;
164     }
165
166     private void disposeApiClient() {
167         if (apiClient != null) {
168             apiClient.logout();
169         }
170         apiClient = null;
171     }
172
173     private void disposeRefreshTask() {
174         if (refreshTask != null) {
175             refreshTask.cancel(true);
176         }
177     }
178
179     private boolean checkConfig() {
180         String errorMessage = "";
181
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";
188         } else {
189             return true;
190         }
191
192         updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
193         return false;
194     }
195
196     private void startRefreshTask() {
197         disposeRefreshTask();
198
199         refreshTask = scheduler.scheduleWithFixedDelay(this::update, 0, configuration.refreshInterval,
200                 TimeUnit.SECONDS);
201     }
202
203     private void update() {
204         try {
205             apiClient.update();
206             updateAccountStatus(ThingStatus.ONLINE);
207             updateThings();
208         } catch (Exception e) {
209             updateAccountStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
210             logger.debug("Failed to update installation status", e);
211         }
212     }
213
214     private void updateAccountStatus(ThingStatus newStatus) {
215         updateAccountStatus(newStatus, ThingStatusDetail.NONE, null);
216     }
217
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);
223         }
224     }
225
226     private void updateListeners(ThingStatus status) {
227         for (AccountStatusListener listener : listeners) {
228             listener.accountStatusChanged(status);
229         }
230     }
231
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<>();
238
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());
248                     }
249                 }
250             }
251         }
252
253         // Then update the things by type, with pre-filtered info
254         for (Thing handler : getThing().getThings()) {
255             ThingHandler thingHandler = handler.getHandler();
256
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());
261             }
262             if (thingHandler instanceof EvohomeHeatingZoneHandler) {
263                 EvohomeHeatingZoneHandler zoneHandler = (EvohomeHeatingZoneHandler) thingHandler;
264                 zoneHandler.update(idToTcsThingsStatusMap.get(zoneIdToTcsIdMap.get(zoneHandler.getId())),
265                         idToZoneMap.get(zoneHandler.getId()));
266             }
267         }
268     }
269 }