]> git.basschouten.com Git - openhab-addons.git/blob
21216755e35be83738fb5acf3640f7fe222c5c1d
[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.tesla.internal.handler;
14
15 import static org.openhab.binding.tesla.internal.TeslaBindingConstants.*;
16
17 import java.io.IOException;
18 import java.nio.charset.StandardCharsets;
19 import java.time.Instant;
20 import java.time.ZoneId;
21 import java.time.format.DateTimeFormatter;
22 import java.util.Base64;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Set;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.locks.ReentrantLock;
31
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.ClientRequestContext;
34 import javax.ws.rs.client.ClientRequestFilter;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.WebTarget;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40
41 import org.openhab.binding.tesla.internal.TeslaBindingConstants;
42 import org.openhab.binding.tesla.internal.discovery.TeslaVehicleDiscoveryService;
43 import org.openhab.binding.tesla.internal.protocol.Vehicle;
44 import org.openhab.binding.tesla.internal.protocol.VehicleConfig;
45 import org.openhab.binding.tesla.internal.protocol.sso.TokenResponse;
46 import org.openhab.core.config.core.Configuration;
47 import org.openhab.core.io.net.http.HttpClientFactory;
48 import org.openhab.core.thing.Bridge;
49 import org.openhab.core.thing.ChannelUID;
50 import org.openhab.core.thing.Thing;
51 import org.openhab.core.thing.ThingStatus;
52 import org.openhab.core.thing.ThingStatusDetail;
53 import org.openhab.core.thing.ThingStatusInfo;
54 import org.openhab.core.thing.binding.BaseBridgeHandler;
55 import org.openhab.core.thing.binding.ThingHandlerService;
56 import org.openhab.core.types.Command;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 import com.google.gson.Gson;
61 import com.google.gson.JsonObject;
62 import com.google.gson.JsonParser;
63
64 /**
65  * The {@link TeslaAccountHandler} is responsible for handling commands, which are sent
66  * to one of the channels.
67  *
68  * @author Karel Goderis - Initial contribution
69  * @author Nicolai Grødum - Adding token based auth
70  * @author Kai Kreuzer - refactored to use separate vehicle handlers
71  */
72 public class TeslaAccountHandler extends BaseBridgeHandler {
73
74     public static final int API_MAXIMUM_ERRORS_IN_INTERVAL = 2;
75     public static final int API_ERROR_INTERVAL_SECONDS = 15;
76     private static final int CONNECT_RETRY_INTERVAL = 15000;
77     private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
78             .withZone(ZoneId.systemDefault());
79
80     private final Logger logger = LoggerFactory.getLogger(TeslaAccountHandler.class);
81
82     // REST Client API variables
83     private final WebTarget teslaTarget;
84     WebTarget vehiclesTarget; // this cannot be marked final as it is used in the runnable
85     final WebTarget vehicleTarget;
86     final WebTarget dataRequestTarget;
87     final WebTarget commandTarget;
88     final WebTarget wakeUpTarget;
89
90     private final TeslaSSOHandler ssoHandler;
91
92     // Threading and Job related variables
93     protected ScheduledFuture<?> connectJob;
94
95     protected long lastTimeStamp;
96     protected long apiIntervalTimestamp;
97     protected int apiIntervalErrors;
98     protected long eventIntervalTimestamp;
99     protected int eventIntervalErrors;
100     protected ReentrantLock lock;
101
102     private final Gson gson = new Gson();
103
104     private TokenResponse logonToken;
105     private final Set<VehicleListener> vehicleListeners = new HashSet<>();
106
107     public TeslaAccountHandler(Bridge bridge, Client teslaClient, HttpClientFactory httpClientFactory) {
108         super(bridge);
109         this.teslaTarget = teslaClient.target(URI_OWNERS);
110         this.ssoHandler = new TeslaSSOHandler(httpClientFactory.getCommonHttpClient());
111
112         this.vehiclesTarget = teslaTarget.path(API_VERSION).path(VEHICLES);
113         this.vehicleTarget = vehiclesTarget.path(PATH_VEHICLE_ID);
114         this.dataRequestTarget = vehicleTarget.path(PATH_DATA_REQUEST);
115         this.commandTarget = vehicleTarget.path(PATH_COMMAND);
116         this.wakeUpTarget = vehicleTarget.path(PATH_WAKE_UP);
117     }
118
119     @Override
120     public void initialize() {
121         logger.trace("Initializing the Tesla account handler for {}", this.getStorageKey());
122
123         updateStatus(ThingStatus.UNKNOWN);
124
125         lock = new ReentrantLock();
126         lock.lock();
127
128         try {
129             if (connectJob == null || connectJob.isCancelled()) {
130                 connectJob = scheduler.scheduleWithFixedDelay(connectRunnable, 0, CONNECT_RETRY_INTERVAL,
131                         TimeUnit.MILLISECONDS);
132             }
133         } finally {
134             lock.unlock();
135         }
136     }
137
138     @Override
139     public void dispose() {
140         logger.trace("Disposing the Tesla account handler for {}", getThing().getUID());
141
142         lock.lock();
143         try {
144             if (connectJob != null && !connectJob.isCancelled()) {
145                 connectJob.cancel(true);
146                 connectJob = null;
147             }
148         } finally {
149             lock.unlock();
150         }
151     }
152
153     public void scanForVehicles() {
154         scheduler.execute(() -> queryVehicles());
155     }
156
157     public void addVehicleListener(VehicleListener listener) {
158         this.vehicleListeners.add(listener);
159     }
160
161     public void removeVehicleListener(VehicleListener listener) {
162         this.vehicleListeners.remove(listener);
163     }
164
165     @Override
166     public void handleCommand(ChannelUID channelUID, Command command) {
167         // we do not have any channels -> nothing to do here
168     }
169
170     public String getAuthHeader() {
171         if (logonToken != null) {
172             return "Bearer " + logonToken.access_token;
173         } else {
174             return null;
175         }
176     }
177
178     protected boolean checkResponse(Response response, boolean immediatelyFail) {
179         if (response != null && response.getStatus() == 200) {
180             return true;
181         } else {
182             apiIntervalErrors++;
183             if (immediatelyFail || apiIntervalErrors >= API_MAXIMUM_ERRORS_IN_INTERVAL) {
184                 if (immediatelyFail) {
185                     logger.warn("Got an unsuccessful result, setting vehicle to offline and will try again");
186                 } else {
187                     logger.warn("Reached the maximum number of errors ({}) for the current interval ({} seconds)",
188                             API_MAXIMUM_ERRORS_IN_INTERVAL, API_ERROR_INTERVAL_SECONDS);
189                 }
190
191                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
192             } else if ((System.currentTimeMillis() - apiIntervalTimestamp) > 1000 * API_ERROR_INTERVAL_SECONDS) {
193                 logger.trace("Resetting the error counter. ({} errors in the last interval)", apiIntervalErrors);
194                 apiIntervalTimestamp = System.currentTimeMillis();
195                 apiIntervalErrors = 0;
196             }
197         }
198
199         return false;
200     }
201
202     protected Vehicle[] queryVehicles() {
203         String authHeader = getAuthHeader();
204
205         if (authHeader != null) {
206             // get a list of vehicles
207             Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
208                     .header("Authorization", authHeader).get();
209
210             logger.debug("Querying the vehicle: Response: {}:{}", response.getStatus(), response.getStatusInfo());
211
212             if (!checkResponse(response, true)) {
213                 logger.error("An error occurred while querying the vehicle");
214                 return null;
215             }
216
217             JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
218             Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
219
220             for (Vehicle vehicle : vehicleArray) {
221                 String responseString = invokeAndParse(vehicle.id, VEHICLE_CONFIG, null, dataRequestTarget);
222                 if (responseString == null || responseString.isBlank()) {
223                     continue;
224                 }
225                 VehicleConfig vehicleConfig = gson.fromJson(responseString, VehicleConfig.class);
226                 for (VehicleListener listener : vehicleListeners) {
227                     listener.vehicleFound(vehicle, vehicleConfig);
228                 }
229                 for (Thing vehicleThing : getThing().getThings()) {
230                     if (vehicle.vin.equals(vehicleThing.getConfiguration().get(VIN))) {
231                         TeslaVehicleHandler vehicleHandler = (TeslaVehicleHandler) vehicleThing.getHandler();
232                         if (vehicleHandler != null) {
233                             logger.debug("Querying the vehicle: VIN {}", vehicle.vin);
234                             String vehicleJSON = gson.toJson(vehicle);
235                             vehicleHandler.parseAndUpdate("queryVehicle", null, vehicleJSON);
236                             logger.trace("Vehicle is id {}/vehicle_id {}/tokens {}", vehicle.id, vehicle.vehicle_id,
237                                     vehicle.tokens);
238                         }
239                     }
240                 }
241             }
242             return vehicleArray;
243         } else {
244             return new Vehicle[0];
245         }
246     }
247
248     private String getStorageKey() {
249         return this.getThing().getUID().getId();
250     }
251
252     private ThingStatusInfo authenticate() {
253         TokenResponse token = logonToken;
254
255         boolean hasExpired = true;
256
257         if (token != null) {
258             Instant tokenCreationInstant = Instant.ofEpochMilli(token.created_at * 1000);
259             logger.debug("Found a request token created at {}", dateFormatter.format(tokenCreationInstant));
260             Instant tokenExpiresInstant = Instant.ofEpochMilli(token.created_at * 1000 + 60 * token.expires_in);
261
262             if (tokenExpiresInstant.isBefore(Instant.now())) {
263                 logger.debug("The token has expired at {}", dateFormatter.format(tokenExpiresInstant));
264                 hasExpired = true;
265             } else {
266                 hasExpired = false;
267             }
268         }
269
270         if (hasExpired) {
271             String username = (String) getConfig().get(CONFIG_USERNAME);
272             String password = (String) getConfig().get(CONFIG_PASSWORD);
273             String refreshToken = (String) getConfig().get(CONFIG_REFRESHTOKEN);
274
275             if (refreshToken == null || refreshToken.isEmpty()) {
276                 if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
277                     try {
278                         refreshToken = ssoHandler.authenticate(username, password);
279                     } catch (Exception e) {
280                         logger.error("An exception occurred while obtaining refresh token with username/password: '{}'",
281                                 e.getMessage());
282                     }
283
284                     if (refreshToken != null) {
285                         // store refresh token from SSO endpoint in config, clear the password
286                         Configuration cfg = editConfiguration();
287                         cfg.put(TeslaBindingConstants.CONFIG_REFRESHTOKEN, refreshToken);
288                         cfg.remove(TeslaBindingConstants.CONFIG_PASSWORD);
289                         updateConfiguration(cfg);
290                     } else {
291                         return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
292                                 "Failed to obtain refresh token with username/password.");
293                     }
294                 } else {
295                     return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
296                             "Neither a refresh token nor credentials are provided.");
297                 }
298             }
299
300             this.logonToken = ssoHandler.getAccessToken(refreshToken);
301             if (this.logonToken == null) {
302                 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
303                         "Failed to obtain access token for API.");
304             }
305         }
306
307         return new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
308     }
309
310     protected String invokeAndParse(String vehicleId, String command, String payLoad, WebTarget target) {
311         logger.debug("Invoking: {}", command);
312
313         if (vehicleId != null) {
314             Response response;
315
316             if (payLoad != null) {
317                 if (command != null) {
318                     response = target.resolveTemplate("cmd", command).resolveTemplate("vid", vehicleId).request()
319                             .header("Authorization", "Bearer " + logonToken.access_token)
320                             .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
321                 } else {
322                     response = target.resolveTemplate("vid", vehicleId).request()
323                             .header("Authorization", "Bearer " + logonToken.access_token)
324                             .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
325                 }
326             } else {
327                 if (command != null) {
328                     response = target.resolveTemplate("cmd", command).resolveTemplate("vid", vehicleId)
329                             .request(MediaType.APPLICATION_JSON_TYPE)
330                             .header("Authorization", "Bearer " + logonToken.access_token).get();
331                 } else {
332                     response = target.resolveTemplate("vid", vehicleId).request(MediaType.APPLICATION_JSON_TYPE)
333                             .header("Authorization", "Bearer " + logonToken.access_token).get();
334                 }
335             }
336
337             if (!checkResponse(response, false)) {
338                 logger.debug("An error occurred while communicating with the vehicle during request {}: {}:{}", command,
339                         (response != null) ? response.getStatus() : "",
340                         (response != null) ? response.getStatusInfo() : "No Response");
341                 return null;
342             }
343
344             try {
345                 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
346                 logger.trace("Request : {}:{}:{} yields {}", command, payLoad, target, jsonObject.get("response"));
347                 return jsonObject.get("response").toString();
348             } catch (Exception e) {
349                 logger.error("An exception occurred while invoking a REST request: '{}'", e.getMessage());
350             }
351         }
352
353         return null;
354     }
355
356     protected Runnable connectRunnable = () -> {
357         try {
358             lock.lock();
359
360             ThingStatusInfo status = getThing().getStatusInfo();
361             if (status.getStatus() != ThingStatus.ONLINE
362                     && status.getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR) {
363                 logger.debug("Setting up an authenticated connection to the Tesla back-end");
364
365                 ThingStatusInfo authenticationResult = authenticate();
366                 updateStatus(authenticationResult.getStatus(), authenticationResult.getStatusDetail(),
367                         authenticationResult.getDescription());
368
369                 if (authenticationResult.getStatus() == ThingStatus.ONLINE) {
370                     // get a list of vehicles
371                     Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
372                             .header("Authorization", "Bearer " + logonToken.access_token).get();
373
374                     if (response != null && response.getStatus() == 200 && response.hasEntity()) {
375                         updateStatus(ThingStatus.ONLINE);
376                         for (Vehicle vehicle : queryVehicles()) {
377                             Bridge bridge = getBridge();
378                             if (bridge != null) {
379                                 List<Thing> things = bridge.getThings();
380                                 for (int i = 0; i < things.size(); i++) {
381                                     Thing thing = things.get(i);
382                                     TeslaVehicleHandler handler = (TeslaVehicleHandler) thing.getHandler();
383                                     if (handler != null) {
384                                         if (vehicle.vin.equals(thing.getConfiguration().get(VIN))) {
385                                             logger.debug(
386                                                     "Found the vehicle with VIN '{}' in the list of vehicles you own",
387                                                     getConfig().get(VIN));
388                                             apiIntervalErrors = 0;
389                                             apiIntervalTimestamp = System.currentTimeMillis();
390                                         } else {
391                                             logger.warn(
392                                                     "Unable to find the vehicle with VIN '{}' in the list of vehicles you own",
393                                                     getConfig().get(VIN));
394                                             handler.updateStatus(ThingStatus.OFFLINE,
395                                                     ThingStatusDetail.CONFIGURATION_ERROR,
396                                                     "Vin is not available through this account.");
397                                         }
398                                     }
399                                 }
400                             }
401                         }
402                     } else {
403                         if (response != null) {
404                             logger.error("Error fetching the list of vehicles : {}:{}", response.getStatus(),
405                                     response.getStatusInfo());
406                             updateStatus(ThingStatus.OFFLINE);
407                         }
408                     }
409                 } else if (authenticationResult.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR) {
410                     // make sure to set thing to CONFIGURATION_ERROR in case of failed authentication in order not to
411                     // hit request limit on retries on the Tesla SSO endpoints.
412                     updateStatus(ThingStatus.OFFLINE, authenticationResult.getStatusDetail());
413                 }
414
415             }
416         } catch (Exception e) {
417             logger.error("An exception occurred while connecting to the Tesla back-end: '{}'", e.getMessage(), e);
418         } finally {
419             lock.unlock();
420         }
421     };
422
423     public static class Authenticator implements ClientRequestFilter {
424         private final String user;
425         private final String password;
426
427         public Authenticator(String user, String password) {
428             this.user = user;
429             this.password = password;
430         }
431
432         @Override
433         public void filter(ClientRequestContext requestContext) throws IOException {
434             MultivaluedMap<String, Object> headers = requestContext.getHeaders();
435             final String basicAuthentication = getBasicAuthentication();
436             headers.add("Authorization", basicAuthentication);
437         }
438
439         private String getBasicAuthentication() {
440             String token = this.user + ":" + this.password;
441             return "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8));
442         }
443     }
444
445     protected class Request implements Runnable {
446
447         private TeslaVehicleHandler handler;
448         private String request;
449         private String payLoad;
450         private WebTarget target;
451
452         public Request(TeslaVehicleHandler handler, String request, String payLoad, WebTarget target) {
453             this.handler = handler;
454             this.request = request;
455             this.payLoad = payLoad;
456             this.target = target;
457         }
458
459         @Override
460         public void run() {
461             try {
462                 String result = "";
463
464                 if (getThing().getStatus() == ThingStatus.ONLINE) {
465                     result = invokeAndParse(handler.getVehicleId(), request, payLoad, target);
466                     if (result != null && !"".equals(result)) {
467                         handler.parseAndUpdate(request, payLoad, result);
468                     }
469                 }
470             } catch (Exception e) {
471                 logger.error("An exception occurred while executing a request to the vehicle: '{}'", e.getMessage(), e);
472             }
473         }
474     }
475
476     public Request newRequest(TeslaVehicleHandler teslaVehicleHandler, String command, String payLoad,
477             WebTarget target) {
478         return new Request(teslaVehicleHandler, command, payLoad, target);
479     }
480
481     @Override
482     public Collection<Class<? extends ThingHandlerService>> getServices() {
483         return Collections.singletonList(TeslaVehicleDiscoveryService.class);
484     }
485 }