2 * Copyright (c) 2010-2021 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.tesla.internal.handler;
15 import static org.openhab.binding.tesla.internal.TeslaBindingConstants.*;
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;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.locks.ReentrantLock;
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;
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;
60 import com.google.gson.Gson;
61 import com.google.gson.JsonObject;
62 import com.google.gson.JsonParser;
65 * The {@link TeslaAccountHandler} is responsible for handling commands, which are sent
66 * to one of the channels.
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
72 public class TeslaAccountHandler extends BaseBridgeHandler {
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());
80 private final Logger logger = LoggerFactory.getLogger(TeslaAccountHandler.class);
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;
90 private final TeslaSSOHandler ssoHandler;
92 // Threading and Job related variables
93 protected ScheduledFuture<?> connectJob;
95 protected long lastTimeStamp;
96 protected long apiIntervalTimestamp;
97 protected int apiIntervalErrors;
98 protected long eventIntervalTimestamp;
99 protected int eventIntervalErrors;
100 protected ReentrantLock lock;
102 private final Gson gson = new Gson();
104 private TokenResponse logonToken;
105 private final Set<VehicleListener> vehicleListeners = new HashSet<>();
107 public TeslaAccountHandler(Bridge bridge, Client teslaClient, HttpClientFactory httpClientFactory) {
109 this.teslaTarget = teslaClient.target(URI_OWNERS);
110 this.ssoHandler = new TeslaSSOHandler(httpClientFactory.getCommonHttpClient());
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);
120 public void initialize() {
121 logger.trace("Initializing the Tesla account handler for {}", this.getStorageKey());
123 updateStatus(ThingStatus.UNKNOWN);
125 lock = new ReentrantLock();
129 if (connectJob == null || connectJob.isCancelled()) {
130 connectJob = scheduler.scheduleWithFixedDelay(connectRunnable, 0, CONNECT_RETRY_INTERVAL,
131 TimeUnit.MILLISECONDS);
139 public void dispose() {
140 logger.trace("Disposing the Tesla account handler for {}", getThing().getUID());
144 if (connectJob != null && !connectJob.isCancelled()) {
145 connectJob.cancel(true);
153 public void scanForVehicles() {
154 scheduler.execute(() -> queryVehicles());
157 public void addVehicleListener(VehicleListener listener) {
158 this.vehicleListeners.add(listener);
161 public void removeVehicleListener(VehicleListener listener) {
162 this.vehicleListeners.remove(listener);
166 public void handleCommand(ChannelUID channelUID, Command command) {
167 // we do not have any channels -> nothing to do here
170 public String getAuthHeader() {
171 if (logonToken != null) {
172 return "Bearer " + logonToken.access_token;
178 protected boolean checkResponse(Response response, boolean immediatelyFail) {
179 if (response != null && response.getStatus() == 200) {
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");
187 logger.warn("Reached the maximum number of errors ({}) for the current interval ({} seconds)",
188 API_MAXIMUM_ERRORS_IN_INTERVAL, API_ERROR_INTERVAL_SECONDS);
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;
202 protected Vehicle[] queryVehicles() {
203 String authHeader = getAuthHeader();
205 if (authHeader != null) {
206 // get a list of vehicles
207 Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
208 .header("Authorization", authHeader).get();
210 logger.debug("Querying the vehicle: Response: {}:{}", response.getStatus(), response.getStatusInfo());
212 if (!checkResponse(response, true)) {
213 logger.error("An error occurred while querying the vehicle");
217 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
218 Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
220 for (Vehicle vehicle : vehicleArray) {
221 String responseString = invokeAndParse(vehicle.id, VEHICLE_CONFIG, null, dataRequestTarget);
222 if (responseString == null || responseString.isBlank()) {
225 VehicleConfig vehicleConfig = gson.fromJson(responseString, VehicleConfig.class);
226 for (VehicleListener listener : vehicleListeners) {
227 listener.vehicleFound(vehicle, vehicleConfig);
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,
244 return new Vehicle[0];
248 private String getStorageKey() {
249 return this.getThing().getUID().getId();
252 private ThingStatusInfo authenticate() {
253 TokenResponse token = logonToken;
255 boolean hasExpired = true;
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);
262 if (tokenExpiresInstant.isBefore(Instant.now())) {
263 logger.debug("The token has expired at {}", dateFormatter.format(tokenExpiresInstant));
271 String username = (String) getConfig().get(CONFIG_USERNAME);
272 String password = (String) getConfig().get(CONFIG_PASSWORD);
273 String refreshToken = (String) getConfig().get(CONFIG_REFRESHTOKEN);
275 if (refreshToken == null || refreshToken.isEmpty()) {
276 if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
278 refreshToken = ssoHandler.authenticate(username, password);
279 } catch (Exception e) {
280 logger.error("An exception occurred while obtaining refresh token with username/password: '{}'",
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);
291 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
292 "Failed to obtain refresh token with username/password.");
295 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
296 "Neither a refresh token nor credentials are provided.");
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.");
307 return new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
310 protected String invokeAndParse(String vehicleId, String command, String payLoad, WebTarget target) {
311 logger.debug("Invoking: {}", command);
313 if (vehicleId != null) {
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));
322 response = target.resolveTemplate("vid", vehicleId).request()
323 .header("Authorization", "Bearer " + logonToken.access_token)
324 .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
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();
332 response = target.resolveTemplate("vid", vehicleId).request(MediaType.APPLICATION_JSON_TYPE)
333 .header("Authorization", "Bearer " + logonToken.access_token).get();
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");
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());
356 protected Runnable connectRunnable = () -> {
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");
365 ThingStatusInfo authenticationResult = authenticate();
366 updateStatus(authenticationResult.getStatus(), authenticationResult.getStatusDetail(),
367 authenticationResult.getDescription());
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();
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))) {
386 "Found the vehicle with VIN '{}' in the list of vehicles you own",
387 getConfig().get(VIN));
388 apiIntervalErrors = 0;
389 apiIntervalTimestamp = System.currentTimeMillis();
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.");
403 if (response != null) {
404 logger.error("Error fetching the list of vehicles : {}:{}", response.getStatus(),
405 response.getStatusInfo());
406 updateStatus(ThingStatus.OFFLINE);
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());
416 } catch (Exception e) {
417 logger.error("An exception occurred while connecting to the Tesla back-end: '{}'", e.getMessage(), e);
423 public static class Authenticator implements ClientRequestFilter {
424 private final String user;
425 private final String password;
427 public Authenticator(String user, String password) {
429 this.password = password;
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);
439 private String getBasicAuthentication() {
440 String token = this.user + ":" + this.password;
441 return "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8));
445 protected class Request implements Runnable {
447 private TeslaVehicleHandler handler;
448 private String request;
449 private String payLoad;
450 private WebTarget target;
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;
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);
470 } catch (Exception e) {
471 logger.error("An exception occurred while executing a request to the vehicle: '{}'", e.getMessage(), e);
476 public Request newRequest(TeslaVehicleHandler teslaVehicleHandler, String command, String payLoad,
478 return new Request(teslaVehicleHandler, command, payLoad, target);
482 public Collection<Class<? extends ThingHandlerService>> getServices() {
483 return Collections.singletonList(TeslaVehicleDiscoveryService.class);