2 * Copyright (c) 2010-2023 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.time.Instant;
18 import java.time.ZoneId;
19 import java.time.format.DateTimeFormatter;
20 import java.util.Collection;
21 import java.util.HashSet;
22 import java.util.List;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.locks.ReentrantLock;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.Entity;
30 import javax.ws.rs.client.WebTarget;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.Response;
34 import org.openhab.binding.tesla.internal.TeslaBindingConstants;
35 import org.openhab.binding.tesla.internal.discovery.TeslaVehicleDiscoveryService;
36 import org.openhab.binding.tesla.internal.protocol.Vehicle;
37 import org.openhab.binding.tesla.internal.protocol.VehicleConfig;
38 import org.openhab.binding.tesla.internal.protocol.VehicleData;
39 import org.openhab.binding.tesla.internal.protocol.sso.TokenResponse;
40 import org.openhab.core.io.net.http.HttpClientFactory;
41 import org.openhab.core.thing.Bridge;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.Thing;
44 import org.openhab.core.thing.ThingStatus;
45 import org.openhab.core.thing.ThingStatusDetail;
46 import org.openhab.core.thing.ThingStatusInfo;
47 import org.openhab.core.thing.ThingTypeMigrationService;
48 import org.openhab.core.thing.binding.BaseBridgeHandler;
49 import org.openhab.core.thing.binding.ThingHandlerService;
50 import org.openhab.core.types.Command;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 import com.google.gson.Gson;
55 import com.google.gson.JsonObject;
56 import com.google.gson.JsonParser;
59 * The {@link TeslaAccountHandler} is responsible for handling commands, which are sent
60 * to one of the channels.
62 * @author Karel Goderis - Initial contribution
63 * @author Nicolai Grødum - Adding token based auth
64 * @author Kai Kreuzer - refactored to use separate vehicle handlers
66 public class TeslaAccountHandler extends BaseBridgeHandler {
68 public static final int API_MAXIMUM_ERRORS_IN_INTERVAL = 3;
69 public static final int API_ERROR_INTERVAL_SECONDS = 15;
70 private static final int CONNECT_RETRY_INTERVAL = 15000;
71 private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
72 .withZone(ZoneId.systemDefault());
74 private final Logger logger = LoggerFactory.getLogger(TeslaAccountHandler.class);
76 // REST Client API variables
77 private final WebTarget teslaTarget;
78 WebTarget vehiclesTarget; // this cannot be marked final as it is used in the runnable
79 final WebTarget vehicleTarget;
80 final WebTarget dataRequestTarget;
81 final WebTarget commandTarget;
82 final WebTarget wakeUpTarget;
84 private final TeslaSSOHandler ssoHandler;
85 private final ThingTypeMigrationService thingTypeMigrationService;
87 // Threading and Job related variables
88 protected ScheduledFuture<?> connectJob;
90 protected long lastTimeStamp;
91 protected long apiIntervalTimestamp;
92 protected int apiIntervalErrors;
93 protected long eventIntervalTimestamp;
94 protected int eventIntervalErrors;
95 protected ReentrantLock lock;
97 private final Gson gson = new Gson();
99 private TokenResponse logonToken;
100 private final Set<VehicleListener> vehicleListeners = new HashSet<>();
102 public TeslaAccountHandler(Bridge bridge, Client teslaClient, HttpClientFactory httpClientFactory,
103 ThingTypeMigrationService thingTypeMigrationService) {
105 this.teslaTarget = teslaClient.target(URI_OWNERS);
106 this.ssoHandler = new TeslaSSOHandler(httpClientFactory.getCommonHttpClient());
107 this.thingTypeMigrationService = thingTypeMigrationService;
109 this.vehiclesTarget = teslaTarget.path(API_VERSION).path(VEHICLES);
110 this.vehicleTarget = vehiclesTarget.path(PATH_VEHICLE_ID);
111 this.dataRequestTarget = vehicleTarget.path(PATH_DATA_REQUEST);
112 this.commandTarget = vehicleTarget.path(PATH_COMMAND);
113 this.wakeUpTarget = vehicleTarget.path(PATH_WAKE_UP);
117 public void initialize() {
118 logger.debug("Initializing the Tesla account handler for {}", this.getStorageKey());
120 updateStatus(ThingStatus.UNKNOWN);
122 lock = new ReentrantLock();
126 if (connectJob == null || connectJob.isCancelled()) {
127 connectJob = scheduler.scheduleWithFixedDelay(connectRunnable, 0, CONNECT_RETRY_INTERVAL,
128 TimeUnit.MILLISECONDS);
136 public void dispose() {
137 logger.debug("Disposing the Tesla account handler for {}", getThing().getUID());
141 if (connectJob != null && !connectJob.isCancelled()) {
142 connectJob.cancel(true);
150 public void scanForVehicles() {
151 scheduler.execute(this::queryVehicles);
154 public void addVehicleListener(VehicleListener listener) {
155 this.vehicleListeners.add(listener);
158 public void removeVehicleListener(VehicleListener listener) {
159 this.vehicleListeners.remove(listener);
163 public void handleCommand(ChannelUID channelUID, Command command) {
164 // we do not have any channels -> nothing to do here
167 public String getAuthHeader() {
168 if (logonToken != null) {
169 return "Bearer " + logonToken.access_token;
175 public String getAccessToken() {
176 return logonToken.access_token;
179 protected boolean checkResponse(Response response, boolean immediatelyFail) {
180 if (response != null && response.getStatus() == 200) {
182 } else if (response != null && response.getStatus() == 401) {
183 logger.debug("The access token has expired, trying to get a new one.");
184 ThingStatusInfo authenticationResult = authenticate();
185 updateStatus(authenticationResult.getStatus(), authenticationResult.getStatusDetail(),
186 authenticationResult.getDescription());
189 if (immediatelyFail || apiIntervalErrors >= API_MAXIMUM_ERRORS_IN_INTERVAL) {
190 if (immediatelyFail) {
191 logger.warn("Got an unsuccessful result, setting vehicle to offline and will try again");
193 logger.warn("Reached the maximum number of errors ({}) for the current interval ({} seconds)",
194 API_MAXIMUM_ERRORS_IN_INTERVAL, API_ERROR_INTERVAL_SECONDS);
195 apiIntervalErrors = 0;
197 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
198 } else if ((System.currentTimeMillis() - apiIntervalTimestamp) > 1000 * API_ERROR_INTERVAL_SECONDS) {
199 logger.trace("Resetting the error counter. ({} errors in the last interval)", apiIntervalErrors);
200 apiIntervalTimestamp = System.currentTimeMillis();
201 apiIntervalErrors = 0;
208 protected Vehicle[] queryVehicles() {
209 String authHeader = getAuthHeader();
211 if (authHeader != null) {
212 // get a list of vehicles
213 Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
214 .header("Authorization", authHeader).get();
216 logger.debug("Querying the vehicle: Response: {}: {}", response.getStatus(),
217 response.getStatusInfo().getReasonPhrase());
219 if (!checkResponse(response, true)) {
220 logger.debug("An error occurred while querying the vehicle");
224 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
225 Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
227 for (Vehicle vehicle : vehicleArray) {
228 String responseString = invokeAndParse(vehicle.id, null, null, dataRequestTarget, 0);
229 VehicleConfig vehicleConfig = null;
230 if (responseString != null && !responseString.isBlank()) {
231 vehicleConfig = gson.fromJson(responseString, VehicleData.class).vehicle_config;
233 for (VehicleListener listener : vehicleListeners) {
234 listener.vehicleFound(vehicle, vehicleConfig);
236 for (Thing vehicleThing : getThing().getThings()) {
237 if (vehicle.vin.equals(vehicleThing.getConfiguration().get(VIN))) {
238 TeslaVehicleHandler vehicleHandler = (TeslaVehicleHandler) vehicleThing.getHandler();
239 if (vehicleHandler != null) {
240 if (TeslaBindingConstants.THING_TYPE_VEHICLE.equals(vehicleThing.getThingTypeUID())
241 && vehicleConfig != null) {
242 // Seems the type of this vehicle has not been identified before, so let's switch the
244 thingTypeMigrationService.migrateThingType(vehicleThing, vehicleConfig.identifyModel(),
245 vehicleThing.getConfiguration());
248 logger.debug("Querying the vehicle: VIN {}", vehicle.vin);
249 String vehicleJSON = gson.toJson(vehicle);
250 vehicleHandler.parseAndUpdate("queryVehicle", null, vehicleJSON);
251 logger.trace("Vehicle is id {}/vehicle_id {}/tokens {}", vehicle.id, vehicle.vehicle_id,
259 return new Vehicle[0];
263 private String getStorageKey() {
264 return this.getThing().getUID().getId();
267 ThingStatusInfo authenticate() {
268 TokenResponse token = logonToken;
270 boolean hasExpired = true;
271 logger.debug("Current authentication time {}", DATE_FORMATTER.format(Instant.now()));
274 Instant tokenCreationInstant = Instant.ofEpochMilli(token.created_at * 1000);
275 Instant tokenExpiresInstant = Instant.ofEpochMilli((token.created_at + token.expires_in) * 1000);
276 logger.debug("Found a request token from {}", DATE_FORMATTER.format(tokenCreationInstant));
277 logger.debug("Access token expiration time {}", DATE_FORMATTER.format(tokenExpiresInstant));
279 if (tokenExpiresInstant.isBefore(Instant.now())) {
280 logger.debug("The access token has expired");
283 logger.debug("The access token has not expired yet");
289 String refreshToken = (String) getConfig().get(CONFIG_REFRESHTOKEN);
291 if (refreshToken == null || refreshToken.isEmpty()) {
292 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
293 "No refresh token is provided.");
296 this.logonToken = ssoHandler.getAccessToken(refreshToken);
297 if (this.logonToken == null) {
298 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
299 "Failed to obtain access token for API.");
303 return new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
306 protected String invokeAndParse(String vehicleId, String command, String payLoad, WebTarget target,
308 logger.debug("Invoking: {}", command);
310 if (vehicleId != null) {
313 if (payLoad != null) {
314 if (command != null) {
315 response = target.resolveTemplate("cmd", command).resolveTemplate("vid", vehicleId).request()
316 .header("Authorization", "Bearer " + logonToken.access_token)
317 .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
319 response = target.resolveTemplate("vid", vehicleId).request()
320 .header("Authorization", "Bearer " + logonToken.access_token)
321 .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
323 } else if (command != null) {
324 response = target.resolveTemplate("cmd", command).resolveTemplate("vid", vehicleId)
325 .request(MediaType.APPLICATION_JSON_TYPE)
326 .header("Authorization", "Bearer " + logonToken.access_token).get();
328 response = target.resolveTemplate("vid", vehicleId).request(MediaType.APPLICATION_JSON_TYPE)
329 .header("Authorization", "Bearer " + logonToken.access_token).get();
332 if (!checkResponse(response, false)) {
333 logger.debug("An error occurred while communicating with the vehicle during request {}: {}: {}",
334 command, (response != null) ? response.getStatus() : "",
335 (response != null) ? response.getStatusInfo().getReasonPhrase() : "No Response");
336 if (response.getStatus() == 408 && noOfretries > 0) {
338 // we give the vehicle a moment to wake up and try the request again
339 Thread.sleep(TimeUnit.SECONDS.toMillis(API_ERROR_INTERVAL_SECONDS));
340 logger.debug("Retrying to send the command {}.", command);
341 return invokeAndParse(vehicleId, command, payLoad, target, noOfretries - 1);
342 } catch (InterruptedException e) {
349 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
350 logger.trace("Request : {}:{} yields {}", command, payLoad, jsonObject.get("response"));
351 return jsonObject.get("response").toString();
352 } catch (Exception e) {
353 logger.error("An exception occurred while invoking a REST request: '{}'", e.getMessage());
360 protected Runnable connectRunnable = () -> {
364 ThingStatusInfo status = getThing().getStatusInfo();
365 if ((status.getStatus() != ThingStatus.ONLINE
366 && status.getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR)
367 || hasUnidentifiedVehicles()) {
368 logger.debug("Setting up an authenticated connection to the Tesla back-end");
370 ThingStatusInfo authenticationResult = authenticate();
371 updateStatus(authenticationResult.getStatus(), authenticationResult.getStatusDetail(),
372 authenticationResult.getDescription());
374 if (authenticationResult.getStatus() == ThingStatus.ONLINE) {
375 // get a list of vehicles
376 Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
377 .header("Authorization", "Bearer " + logonToken.access_token).get();
379 if (response != null && response.getStatus() == 200 && response.hasEntity()) {
380 updateStatus(ThingStatus.ONLINE);
381 for (Vehicle vehicle : queryVehicles()) {
382 Bridge bridge = getBridge();
383 if (bridge != null) {
384 List<Thing> things = bridge.getThings();
385 for (int i = 0; i < things.size(); i++) {
386 Thing thing = things.get(i);
387 TeslaVehicleHandler handler = (TeslaVehicleHandler) thing.getHandler();
388 if (handler != null) {
389 if (vehicle.vin.equals(thing.getConfiguration().get(VIN))) {
391 "Found the vehicle with VIN '{}' in the list of vehicles you own",
392 getConfig().get(VIN));
393 apiIntervalErrors = 0;
394 apiIntervalTimestamp = System.currentTimeMillis();
397 "Unable to find the vehicle with VIN '{}' in the list of vehicles you own",
398 getConfig().get(VIN));
399 handler.updateStatus(ThingStatus.OFFLINE,
400 ThingStatusDetail.CONFIGURATION_ERROR,
401 "Vin is not available through this account.");
407 } else if (response != null) {
408 logger.error("Error fetching the list of vehicles : {}:{}", response.getStatus(),
409 response.getStatusInfo());
410 updateStatus(ThingStatus.OFFLINE);
412 } else if (authenticationResult.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR) {
413 // make sure to set thing to CONFIGURATION_ERROR in case of failed authentication in order not to
414 // hit request limit on retries on the Tesla SSO endpoints.
415 updateStatus(ThingStatus.OFFLINE, authenticationResult.getStatusDetail());
418 } catch (Exception e) {
419 logger.error("An exception occurred while connecting to the Tesla back-end: '{}'", e.getMessage(), e);
425 private boolean hasUnidentifiedVehicles() {
426 return getThing().getThings().stream()
427 .anyMatch(vehicle -> TeslaBindingConstants.THING_TYPE_VEHICLE.equals(vehicle.getThingTypeUID()));
430 protected class Request implements Runnable {
432 private static final int NO_OF_RETRIES = 3;
434 private TeslaVehicleHandler handler;
435 private String request;
436 private String payLoad;
437 private WebTarget target;
438 private boolean allowWakeUpForCommands;
440 public Request(TeslaVehicleHandler handler, String request, String payLoad, WebTarget target,
441 boolean allowWakeUpForCommands) {
442 this.handler = handler;
443 this.request = request;
444 this.payLoad = payLoad;
445 this.target = target;
446 this.allowWakeUpForCommands = allowWakeUpForCommands;
454 if (getThing().getStatus() == ThingStatus.ONLINE) {
455 result = invokeAndParse(handler.getVehicleId(), request, payLoad, target,
456 allowWakeUpForCommands ? NO_OF_RETRIES : 0);
457 if (result != null && !"".equals(result)) {
458 handler.parseAndUpdate(request, payLoad, result);
461 } catch (Exception e) {
462 logger.error("An exception occurred while executing a request to the vehicle: '{}'", e.getMessage(), e);
467 public Request newRequest(TeslaVehicleHandler teslaVehicleHandler, String command, String payLoad, WebTarget target,
468 boolean allowWakeUpForCommands) {
469 return new Request(teslaVehicleHandler, command, payLoad, target, allowWakeUpForCommands);
473 public Collection<Class<? extends ThingHandlerService>> getServices() {
474 return List.of(TeslaVehicleDiscoveryService.class);