]> git.basschouten.com Git - openhab-addons.git/blob
d4986bda5504d331e96fd6be2b4e2ac7b71f43e6
[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.tesla.internal.handler;
14
15 import static org.openhab.binding.tesla.internal.TeslaBindingConstants.*;
16
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.Collections;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Set;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.locks.ReentrantLock;
28
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.client.WebTarget;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.Response;
34
35 import org.openhab.binding.tesla.internal.TeslaBindingConstants;
36 import org.openhab.binding.tesla.internal.discovery.TeslaVehicleDiscoveryService;
37 import org.openhab.binding.tesla.internal.protocol.Vehicle;
38 import org.openhab.binding.tesla.internal.protocol.VehicleConfig;
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;
53
54 import com.google.gson.Gson;
55 import com.google.gson.JsonObject;
56 import com.google.gson.JsonParser;
57
58 /**
59  * The {@link TeslaAccountHandler} is responsible for handling commands, which are sent
60  * to one of the channels.
61  *
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
65  */
66 public class TeslaAccountHandler extends BaseBridgeHandler {
67
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());
73
74     private final Logger logger = LoggerFactory.getLogger(TeslaAccountHandler.class);
75
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;
83
84     private final TeslaSSOHandler ssoHandler;
85     private final ThingTypeMigrationService thingTypeMigrationService;
86
87     // Threading and Job related variables
88     protected ScheduledFuture<?> connectJob;
89
90     protected long lastTimeStamp;
91     protected long apiIntervalTimestamp;
92     protected int apiIntervalErrors;
93     protected long eventIntervalTimestamp;
94     protected int eventIntervalErrors;
95     protected ReentrantLock lock;
96
97     private final Gson gson = new Gson();
98
99     private TokenResponse logonToken;
100     private final Set<VehicleListener> vehicleListeners = new HashSet<>();
101
102     public TeslaAccountHandler(Bridge bridge, Client teslaClient, HttpClientFactory httpClientFactory,
103             ThingTypeMigrationService thingTypeMigrationService) {
104         super(bridge);
105         this.teslaTarget = teslaClient.target(URI_OWNERS);
106         this.ssoHandler = new TeslaSSOHandler(httpClientFactory.getCommonHttpClient());
107         this.thingTypeMigrationService = thingTypeMigrationService;
108
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);
114     }
115
116     @Override
117     public void initialize() {
118         logger.debug("Initializing the Tesla account handler for {}", this.getStorageKey());
119
120         updateStatus(ThingStatus.UNKNOWN);
121
122         lock = new ReentrantLock();
123         lock.lock();
124
125         try {
126             if (connectJob == null || connectJob.isCancelled()) {
127                 connectJob = scheduler.scheduleWithFixedDelay(connectRunnable, 0, CONNECT_RETRY_INTERVAL,
128                         TimeUnit.MILLISECONDS);
129             }
130         } finally {
131             lock.unlock();
132         }
133     }
134
135     @Override
136     public void dispose() {
137         logger.debug("Disposing the Tesla account handler for {}", getThing().getUID());
138
139         lock.lock();
140         try {
141             if (connectJob != null && !connectJob.isCancelled()) {
142                 connectJob.cancel(true);
143                 connectJob = null;
144             }
145         } finally {
146             lock.unlock();
147         }
148     }
149
150     public void scanForVehicles() {
151         scheduler.execute(this::queryVehicles);
152     }
153
154     public void addVehicleListener(VehicleListener listener) {
155         this.vehicleListeners.add(listener);
156     }
157
158     public void removeVehicleListener(VehicleListener listener) {
159         this.vehicleListeners.remove(listener);
160     }
161
162     @Override
163     public void handleCommand(ChannelUID channelUID, Command command) {
164         // we do not have any channels -> nothing to do here
165     }
166
167     public String getAuthHeader() {
168         if (logonToken != null) {
169             return "Bearer " + logonToken.access_token;
170         } else {
171             return null;
172         }
173     }
174
175     public String getAccessToken() {
176         return logonToken.access_token;
177     }
178
179     protected boolean checkResponse(Response response, boolean immediatelyFail) {
180         if (response != null && response.getStatus() == 200) {
181             return true;
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());
187         } else {
188             apiIntervalErrors++;
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");
192                 } else {
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;
196                 }
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;
202             }
203         }
204
205         return false;
206     }
207
208     protected Vehicle[] queryVehicles() {
209         String authHeader = getAuthHeader();
210
211         if (authHeader != null) {
212             // get a list of vehicles
213             Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
214                     .header("Authorization", authHeader).get();
215
216             logger.debug("Querying the vehicle: Response: {}: {}", response.getStatus(),
217                     response.getStatusInfo().getReasonPhrase());
218
219             if (!checkResponse(response, true)) {
220                 logger.debug("An error occurred while querying the vehicle");
221                 return null;
222             }
223
224             JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
225             Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
226
227             for (Vehicle vehicle : vehicleArray) {
228                 String responseString = invokeAndParse(vehicle.id, VEHICLE_CONFIG, null, dataRequestTarget, 0);
229                 VehicleConfig vehicleConfig = null;
230                 if (responseString != null && !responseString.isBlank()) {
231                     vehicleConfig = gson.fromJson(responseString, VehicleConfig.class);
232                 }
233                 for (VehicleListener listener : vehicleListeners) {
234                     listener.vehicleFound(vehicle, vehicleConfig);
235                 }
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
243                                 // thing type of it
244                                 thingTypeMigrationService.migrateThingType(vehicleThing, vehicleConfig.identifyModel(),
245                                         vehicleThing.getConfiguration());
246                                 break;
247                             }
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,
252                                     vehicle.tokens);
253                         }
254                     }
255                 }
256             }
257             return vehicleArray;
258         } else {
259             return new Vehicle[0];
260         }
261     }
262
263     private String getStorageKey() {
264         return this.getThing().getUID().getId();
265     }
266
267     ThingStatusInfo authenticate() {
268         TokenResponse token = logonToken;
269
270         boolean hasExpired = true;
271         logger.debug("Current authentication time {}", DATE_FORMATTER.format(Instant.now()));
272
273         if (token != null) {
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));
278
279             if (tokenExpiresInstant.isBefore(Instant.now())) {
280                 logger.debug("The access token has expired");
281                 hasExpired = true;
282             } else {
283                 logger.debug("The access token has not expired yet");
284                 hasExpired = false;
285             }
286         }
287
288         if (hasExpired) {
289             String refreshToken = (String) getConfig().get(CONFIG_REFRESHTOKEN);
290
291             if (refreshToken == null || refreshToken.isEmpty()) {
292                 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
293                         "No refresh token is provided.");
294             }
295
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.");
300             }
301         }
302
303         return new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
304     }
305
306     protected String invokeAndParse(String vehicleId, String command, String payLoad, WebTarget target,
307             int noOfretries) {
308         logger.debug("Invoking: {}", command);
309
310         if (vehicleId != null) {
311             Response response;
312
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));
318                 } else {
319                     response = target.resolveTemplate("vid", vehicleId).request()
320                             .header("Authorization", "Bearer " + logonToken.access_token)
321                             .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
322                 }
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();
327             } else {
328                 response = target.resolveTemplate("vid", vehicleId).request(MediaType.APPLICATION_JSON_TYPE)
329                         .header("Authorization", "Bearer " + logonToken.access_token).get();
330             }
331
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) {
337                     try {
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) {
343                     }
344                 }
345                 return null;
346             }
347
348             try {
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());
354             }
355         }
356
357         return null;
358     }
359
360     protected Runnable connectRunnable = () -> {
361         try {
362             lock.lock();
363
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");
369
370                 ThingStatusInfo authenticationResult = authenticate();
371                 updateStatus(authenticationResult.getStatus(), authenticationResult.getStatusDetail(),
372                         authenticationResult.getDescription());
373
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();
378
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))) {
390                                             logger.debug(
391                                                     "Found the vehicle with VIN '{}' in the list of vehicles you own",
392                                                     getConfig().get(VIN));
393                                             apiIntervalErrors = 0;
394                                             apiIntervalTimestamp = System.currentTimeMillis();
395                                         } else {
396                                             logger.warn(
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.");
402                                         }
403                                     }
404                                 }
405                             }
406                         }
407                     } else if (response != null) {
408                         logger.error("Error fetching the list of vehicles : {}:{}", response.getStatus(),
409                                 response.getStatusInfo());
410                         updateStatus(ThingStatus.OFFLINE);
411                     }
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());
416                 }
417             }
418         } catch (Exception e) {
419             logger.error("An exception occurred while connecting to the Tesla back-end: '{}'", e.getMessage(), e);
420         } finally {
421             lock.unlock();
422         }
423     };
424
425     private boolean hasUnidentifiedVehicles() {
426         return getThing().getThings().stream()
427                 .anyMatch(vehicle -> TeslaBindingConstants.THING_TYPE_VEHICLE.equals(vehicle.getThingTypeUID()));
428     }
429
430     protected class Request implements Runnable {
431
432         private static final int NO_OF_RETRIES = 3;
433
434         private TeslaVehicleHandler handler;
435         private String request;
436         private String payLoad;
437         private WebTarget target;
438         private boolean allowWakeUpForCommands;
439
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;
447         }
448
449         @Override
450         public void run() {
451             try {
452                 String result = "";
453
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);
459                     }
460                 }
461             } catch (Exception e) {
462                 logger.error("An exception occurred while executing a request to the vehicle: '{}'", e.getMessage(), e);
463             }
464         }
465     }
466
467     public Request newRequest(TeslaVehicleHandler teslaVehicleHandler, String command, String payLoad, WebTarget target,
468             boolean allowWakeUpForCommands) {
469         return new Request(teslaVehicleHandler, command, payLoad, target, allowWakeUpForCommands);
470     }
471
472     @Override
473     public Collection<Class<? extends ThingHandlerService>> getServices() {
474         return Collections.singletonList(TeslaVehicleDiscoveryService.class);
475     }
476 }