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