]> git.basschouten.com Git - openhab-addons.git/blob
d585231d607de77381d29740382da91f1609636b
[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 dateFormatter = 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(() -> 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             return false;
188         } else {
189             apiIntervalErrors++;
190             if (immediatelyFail || apiIntervalErrors >= API_MAXIMUM_ERRORS_IN_INTERVAL) {
191                 if (immediatelyFail) {
192                     logger.warn("Got an unsuccessful result, setting vehicle to offline and will try again");
193                 } else {
194                     logger.warn("Reached the maximum number of errors ({}) for the current interval ({} seconds)",
195                             API_MAXIMUM_ERRORS_IN_INTERVAL, API_ERROR_INTERVAL_SECONDS);
196                     apiIntervalErrors = 0;
197                 }
198                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
199             } else if ((System.currentTimeMillis() - apiIntervalTimestamp) > 1000 * API_ERROR_INTERVAL_SECONDS) {
200                 logger.trace("Resetting the error counter. ({} errors in the last interval)", apiIntervalErrors);
201                 apiIntervalTimestamp = System.currentTimeMillis();
202                 apiIntervalErrors = 0;
203             }
204         }
205
206         return false;
207     }
208
209     protected Vehicle[] queryVehicles() {
210         String authHeader = getAuthHeader();
211
212         if (authHeader != null) {
213             // get a list of vehicles
214             Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
215                     .header("Authorization", authHeader).get();
216
217             logger.debug("Querying the vehicle: Response: {}: {}", response.getStatus(),
218                     response.getStatusInfo().getReasonPhrase());
219
220             if (!checkResponse(response, true)) {
221                 logger.debug("An error occurred while querying the vehicle");
222                 return null;
223             }
224
225             JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
226             Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
227
228             for (Vehicle vehicle : vehicleArray) {
229                 String responseString = invokeAndParse(vehicle.id, VEHICLE_CONFIG, null, dataRequestTarget, 0);
230                 VehicleConfig vehicleConfig = null;
231                 if (responseString != null && !responseString.isBlank()) {
232                     vehicleConfig = gson.fromJson(responseString, VehicleConfig.class);
233                 }
234                 for (VehicleListener listener : vehicleListeners) {
235                     listener.vehicleFound(vehicle, vehicleConfig);
236                 }
237                 for (Thing vehicleThing : getThing().getThings()) {
238                     if (vehicle.vin.equals(vehicleThing.getConfiguration().get(VIN))) {
239                         TeslaVehicleHandler vehicleHandler = (TeslaVehicleHandler) vehicleThing.getHandler();
240                         if (vehicleHandler != null) {
241                             if (TeslaBindingConstants.THING_TYPE_VEHICLE.equals(vehicleThing.getThingTypeUID())
242                                     && vehicleConfig != null) {
243                                 // Seems the type of this vehicle has not been identified before, so let's switch the
244                                 // thing type of it
245                                 thingTypeMigrationService.migrateThingType(vehicleThing, vehicleConfig.identifyModel(),
246                                         vehicleThing.getConfiguration());
247                                 break;
248
249                             }
250                             logger.debug("Querying the vehicle: VIN {}", vehicle.vin);
251                             String vehicleJSON = gson.toJson(vehicle);
252                             vehicleHandler.parseAndUpdate("queryVehicle", null, vehicleJSON);
253                             logger.trace("Vehicle is id {}/vehicle_id {}/tokens {}", vehicle.id, vehicle.vehicle_id,
254                                     vehicle.tokens);
255                         }
256                     }
257                 }
258             }
259             return vehicleArray;
260         } else {
261             return new Vehicle[0];
262         }
263     }
264
265     private String getStorageKey() {
266         return this.getThing().getUID().getId();
267     }
268
269     ThingStatusInfo authenticate() {
270         TokenResponse token = logonToken;
271
272         boolean hasExpired = true;
273         logger.debug("Current authentication time {}", dateFormatter.format(Instant.now()));
274
275         if (token != null) {
276             Instant tokenCreationInstant = Instant.ofEpochMilli(token.created_at * 1000);
277             Instant tokenExpiresInstant = Instant.ofEpochMilli((token.created_at + token.expires_in) * 1000);
278             logger.debug("Found a request token from {}", dateFormatter.format(tokenCreationInstant));
279             logger.debug("Access token expiration time {}", dateFormatter.format(tokenExpiresInstant));
280
281             if (tokenExpiresInstant.isBefore(Instant.now())) {
282                 logger.debug("The access token has expired");
283                 hasExpired = true;
284             } else {
285                 logger.debug("The access token has not expired yet");
286                 hasExpired = false;
287             }
288         }
289
290         if (hasExpired) {
291             String refreshToken = (String) getConfig().get(CONFIG_REFRESHTOKEN);
292
293             if (refreshToken == null || refreshToken.isEmpty()) {
294                 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
295                         "No refresh token is provided.");
296             }
297
298             this.logonToken = ssoHandler.getAccessToken(refreshToken);
299             if (this.logonToken == null) {
300                 return new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
301                         "Failed to obtain access token for API.");
302             }
303         }
304
305         return new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
306     }
307
308     protected String invokeAndParse(String vehicleId, String command, String payLoad, WebTarget target,
309             int noOfretries) {
310         logger.debug("Invoking: {}", command);
311
312         if (vehicleId != null) {
313             Response response;
314
315             if (payLoad != null) {
316                 if (command != null) {
317                     response = target.resolveTemplate("cmd", command).resolveTemplate("vid", vehicleId).request()
318                             .header("Authorization", "Bearer " + logonToken.access_token)
319                             .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
320                 } else {
321                     response = target.resolveTemplate("vid", vehicleId).request()
322                             .header("Authorization", "Bearer " + logonToken.access_token)
323                             .post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));
324                 }
325             } else {
326                 if (command != null) {
327                     response = target.resolveTemplate("cmd", command).resolveTemplate("vid", vehicleId)
328                             .request(MediaType.APPLICATION_JSON_TYPE)
329                             .header("Authorization", "Bearer " + logonToken.access_token).get();
330                 } else {
331                     response = target.resolveTemplate("vid", vehicleId).request(MediaType.APPLICATION_JSON_TYPE)
332                             .header("Authorization", "Bearer " + logonToken.access_token).get();
333                 }
334             }
335
336             if (!checkResponse(response, false)) {
337                 logger.debug("An error occurred while communicating with the vehicle during request {}: {}: {}",
338                         command, (response != null) ? response.getStatus() : "",
339                         (response != null) ? response.getStatusInfo().getReasonPhrase() : "No Response");
340                 if (response.getStatus() == 408 && noOfretries > 0) {
341                     try {
342                         // we give the vehicle a moment to wake up and try the request again
343                         Thread.sleep(TimeUnit.SECONDS.toMillis(API_ERROR_INTERVAL_SECONDS));
344                         logger.debug("Retrying to send the command {}.", command);
345                         return invokeAndParse(vehicleId, command, payLoad, target, noOfretries - 1);
346                     } catch (InterruptedException e) {
347                         return null;
348                     }
349                 }
350                 return null;
351             }
352
353             try {
354                 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
355                 logger.trace("Request : {}:{} yields {}", command, payLoad, jsonObject.get("response"));
356                 return jsonObject.get("response").toString();
357             } catch (Exception e) {
358                 logger.error("An exception occurred while invoking a REST request: '{}'", e.getMessage());
359             }
360         }
361
362         return null;
363     }
364
365     protected Runnable connectRunnable = () -> {
366         try {
367             lock.lock();
368
369             ThingStatusInfo status = getThing().getStatusInfo();
370             if ((status.getStatus() != ThingStatus.ONLINE
371                     && status.getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR)
372                     || hasUnidentifiedVehicles()) {
373                 logger.debug("Setting up an authenticated connection to the Tesla back-end");
374
375                 ThingStatusInfo authenticationResult = authenticate();
376                 updateStatus(authenticationResult.getStatus(), authenticationResult.getStatusDetail(),
377                         authenticationResult.getDescription());
378
379                 if (authenticationResult.getStatus() == ThingStatus.ONLINE) {
380                     // get a list of vehicles
381                     Response response = vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
382                             .header("Authorization", "Bearer " + logonToken.access_token).get();
383
384                     if (response != null && response.getStatus() == 200 && response.hasEntity()) {
385                         updateStatus(ThingStatus.ONLINE);
386                         for (Vehicle vehicle : queryVehicles()) {
387                             Bridge bridge = getBridge();
388                             if (bridge != null) {
389                                 List<Thing> things = bridge.getThings();
390                                 for (int i = 0; i < things.size(); i++) {
391                                     Thing thing = things.get(i);
392                                     TeslaVehicleHandler handler = (TeslaVehicleHandler) thing.getHandler();
393                                     if (handler != null) {
394                                         if (vehicle.vin.equals(thing.getConfiguration().get(VIN))) {
395                                             logger.debug(
396                                                     "Found the vehicle with VIN '{}' in the list of vehicles you own",
397                                                     getConfig().get(VIN));
398                                             apiIntervalErrors = 0;
399                                             apiIntervalTimestamp = System.currentTimeMillis();
400                                         } else {
401                                             logger.warn(
402                                                     "Unable to find the vehicle with VIN '{}' in the list of vehicles you own",
403                                                     getConfig().get(VIN));
404                                             handler.updateStatus(ThingStatus.OFFLINE,
405                                                     ThingStatusDetail.CONFIGURATION_ERROR,
406                                                     "Vin is not available through this account.");
407                                         }
408                                     }
409                                 }
410                             }
411                         }
412                     } else {
413                         if (response != null) {
414                             logger.error("Error fetching the list of vehicles : {}:{}", response.getStatus(),
415                                     response.getStatusInfo());
416                             updateStatus(ThingStatus.OFFLINE);
417                         }
418                     }
419                 } else if (authenticationResult.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR) {
420                     // make sure to set thing to CONFIGURATION_ERROR in case of failed authentication in order not to
421                     // hit request limit on retries on the Tesla SSO endpoints.
422                     updateStatus(ThingStatus.OFFLINE, authenticationResult.getStatusDetail());
423                 }
424
425             }
426         } catch (Exception e) {
427             logger.error("An exception occurred while connecting to the Tesla back-end: '{}'", e.getMessage(), e);
428         } finally {
429             lock.unlock();
430         }
431     };
432
433     private boolean hasUnidentifiedVehicles() {
434         return getThing().getThings().stream()
435                 .anyMatch(vehicle -> TeslaBindingConstants.THING_TYPE_VEHICLE.equals(vehicle.getThingTypeUID()));
436     }
437
438     protected class Request implements Runnable {
439
440         private static final int NO_OF_RETRIES = 3;
441
442         private TeslaVehicleHandler handler;
443         private String request;
444         private String payLoad;
445         private WebTarget target;
446         private boolean allowWakeUpForCommands;
447
448         public Request(TeslaVehicleHandler handler, String request, String payLoad, WebTarget target,
449                 boolean allowWakeUpForCommands) {
450             this.handler = handler;
451             this.request = request;
452             this.payLoad = payLoad;
453             this.target = target;
454             this.allowWakeUpForCommands = allowWakeUpForCommands;
455         }
456
457         @Override
458         public void run() {
459             try {
460                 String result = "";
461
462                 if (getThing().getStatus() == ThingStatus.ONLINE) {
463                     result = invokeAndParse(handler.getVehicleId(), request, payLoad, target,
464                             allowWakeUpForCommands ? NO_OF_RETRIES : 0);
465                     if (result != null && !"".equals(result)) {
466                         handler.parseAndUpdate(request, payLoad, result);
467                     }
468                 }
469             } catch (Exception e) {
470                 logger.error("An exception occurred while executing a request to the vehicle: '{}'", e.getMessage(), e);
471             }
472         }
473     }
474
475     public Request newRequest(TeslaVehicleHandler teslaVehicleHandler, String command, String payLoad, WebTarget target,
476             boolean allowWakeUpForCommands) {
477         return new Request(teslaVehicleHandler, command, payLoad, target, allowWakeUpForCommands);
478     }
479
480     @Override
481     public Collection<Class<? extends ThingHandlerService>> getServices() {
482         return Collections.singletonList(TeslaVehicleDiscoveryService.class);
483     }
484 }