]> git.basschouten.com Git - openhab-addons.git/blob
8053d47ae1d48272926089b3944fa6fa79b16f4f
[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.io.IOException;
18 import java.math.BigDecimal;
19 import java.math.RoundingMode;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.text.SimpleDateFormat;
23 import java.util.Arrays;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.locks.ReentrantLock;
31 import java.util.stream.Collectors;
32
33 import javax.measure.quantity.Temperature;
34 import javax.ws.rs.ProcessingException;
35 import javax.ws.rs.client.WebTarget;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.openhab.binding.tesla.internal.TeslaBindingConstants;
41 import org.openhab.binding.tesla.internal.TeslaBindingConstants.EventKeys;
42 import org.openhab.binding.tesla.internal.TeslaChannelSelectorProxy;
43 import org.openhab.binding.tesla.internal.TeslaChannelSelectorProxy.TeslaChannelSelector;
44 import org.openhab.binding.tesla.internal.handler.TeslaAccountHandler.Request;
45 import org.openhab.binding.tesla.internal.protocol.ChargeState;
46 import org.openhab.binding.tesla.internal.protocol.ClimateState;
47 import org.openhab.binding.tesla.internal.protocol.DriveState;
48 import org.openhab.binding.tesla.internal.protocol.Event;
49 import org.openhab.binding.tesla.internal.protocol.GUIState;
50 import org.openhab.binding.tesla.internal.protocol.Vehicle;
51 import org.openhab.binding.tesla.internal.protocol.VehicleState;
52 import org.openhab.binding.tesla.internal.throttler.QueueChannelThrottler;
53 import org.openhab.binding.tesla.internal.throttler.Rate;
54 import org.openhab.core.io.net.http.WebSocketFactory;
55 import org.openhab.core.library.types.DecimalType;
56 import org.openhab.core.library.types.IncreaseDecreaseType;
57 import org.openhab.core.library.types.OnOffType;
58 import org.openhab.core.library.types.PercentType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.library.types.StringType;
61 import org.openhab.core.library.unit.SIUnits;
62 import org.openhab.core.library.unit.Units;
63 import org.openhab.core.thing.ChannelUID;
64 import org.openhab.core.thing.Thing;
65 import org.openhab.core.thing.ThingStatus;
66 import org.openhab.core.thing.ThingStatusDetail;
67 import org.openhab.core.thing.binding.BaseThingHandler;
68 import org.openhab.core.types.Command;
69 import org.openhab.core.types.RefreshType;
70 import org.openhab.core.types.State;
71 import org.openhab.core.types.UnDefType;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 import com.google.gson.Gson;
76 import com.google.gson.JsonElement;
77 import com.google.gson.JsonObject;
78 import com.google.gson.JsonParser;
79
80 /**
81  * The {@link TeslaVehicleHandler} is responsible for handling commands, which are sent
82  * to one of the channels of a specific vehicle.
83  *
84  * @author Karel Goderis - Initial contribution
85  * @author Kai Kreuzer - Refactored to use separate account handler and improved configuration options
86  */
87 public class TeslaVehicleHandler extends BaseThingHandler {
88
89     private static final int FAST_STATUS_REFRESH_INTERVAL = 15000;
90     private static final int SLOW_STATUS_REFRESH_INTERVAL = 60000;
91     private static final int API_SLEEP_INTERVAL_MINUTES = 20;
92     private static final int MOVE_THRESHOLD_INTERVAL_MINUTES_DEFAULT = 5;
93     private static final int THRESHOLD_INTERVAL_FOR_ADVANCED_MINUTES = 60;
94     private static final int EVENT_MAXIMUM_ERRORS_IN_INTERVAL = 10;
95     private static final int EVENT_ERROR_INTERVAL_SECONDS = 15;
96     private static final int EVENT_STREAM_PAUSE = 3000;
97     private static final int EVENT_TIMESTAMP_AGE_LIMIT = 3000;
98     private static final int EVENT_TIMESTAMP_MAX_DELTA = 10000;
99     private static final int EVENT_PING_INTERVAL = 10000;
100
101     private final Logger logger = LoggerFactory.getLogger(TeslaVehicleHandler.class);
102
103     // Vehicle state variables
104     protected Vehicle vehicle;
105     protected String vehicleJSON;
106     protected DriveState driveState;
107     protected GUIState guiState;
108     protected VehicleState vehicleState;
109     protected ChargeState chargeState;
110     protected ClimateState climateState;
111
112     protected boolean allowWakeUp;
113     protected boolean allowWakeUpForCommands;
114     protected boolean enableEvents = false;
115     protected boolean useDriveState = false;
116     protected boolean useAdvancedStates = false;
117     protected boolean lastValidDriveStateNotNull = true;
118
119     protected long lastTimeStamp;
120     protected long apiIntervalTimestamp;
121     protected int apiIntervalErrors;
122     protected long eventIntervalTimestamp;
123     protected int eventIntervalErrors;
124     protected int inactivity = MOVE_THRESHOLD_INTERVAL_MINUTES_DEFAULT;
125     protected ReentrantLock lock;
126
127     protected double lastLongitude;
128     protected double lastLatitude;
129     protected long lastLocationChangeTimestamp;
130     protected long lastDriveStateChangeToNullTimestamp;
131     protected long lastAdvModesTimestamp = System.currentTimeMillis();
132     protected long lastStateTimestamp = System.currentTimeMillis();
133     protected int backOffCounter = 0;
134
135     protected String lastState = "";
136     protected boolean isInactive = false;
137
138     protected TeslaAccountHandler account;
139
140     protected QueueChannelThrottler stateThrottler;
141     protected TeslaChannelSelectorProxy teslaChannelSelectorProxy = new TeslaChannelSelectorProxy();
142     protected Thread eventThread;
143     protected ScheduledFuture<?> fastStateJob;
144     protected ScheduledFuture<?> slowStateJob;
145     protected WebSocketFactory webSocketFactory;
146
147     private final Gson gson = new Gson();
148
149     public TeslaVehicleHandler(Thing thing, WebSocketFactory webSocketFactory) {
150         super(thing);
151         this.webSocketFactory = webSocketFactory;
152     }
153
154     @SuppressWarnings("null")
155     @Override
156     public void initialize() {
157         logger.trace("Initializing the Tesla handler for {}", getThing().getUID());
158         updateStatus(ThingStatus.UNKNOWN);
159         allowWakeUp = (boolean) getConfig().get(TeslaBindingConstants.CONFIG_ALLOWWAKEUP);
160         allowWakeUpForCommands = (boolean) getConfig().get(TeslaBindingConstants.CONFIG_ALLOWWAKEUPFORCOMMANDS);
161         enableEvents = (boolean) getConfig().get(TeslaBindingConstants.CONFIG_ENABLEEVENTS);
162         Number inactivityParam = (Number) getConfig().get(TeslaBindingConstants.CONFIG_INACTIVITY);
163         inactivity = inactivityParam == null ? MOVE_THRESHOLD_INTERVAL_MINUTES_DEFAULT : inactivityParam.intValue();
164         Boolean useDriveStateParam = (boolean) getConfig().get(TeslaBindingConstants.CONFIG_USEDRIVESTATE);
165         useDriveState = useDriveStateParam == null ? false : useDriveStateParam;
166         Boolean useAdvancedStatesParam = (boolean) getConfig().get(TeslaBindingConstants.CONFIG_USEDADVANCEDSTATES);
167         useAdvancedStates = useAdvancedStatesParam == null ? false : useAdvancedStatesParam;
168
169         account = (TeslaAccountHandler) getBridge().getHandler();
170         lock = new ReentrantLock();
171         scheduler.execute(() -> queryVehicleAndUpdate());
172
173         lock.lock();
174         try {
175             Map<Object, Rate> channels = new HashMap<>();
176             channels.put(DATA_THROTTLE, new Rate(1, 1, TimeUnit.SECONDS));
177             channels.put(COMMAND_THROTTLE, new Rate(20, 1, TimeUnit.MINUTES));
178
179             Rate firstRate = new Rate(20, 1, TimeUnit.MINUTES);
180             Rate secondRate = new Rate(200, 10, TimeUnit.MINUTES);
181             stateThrottler = new QueueChannelThrottler(firstRate, scheduler, channels);
182             stateThrottler.addRate(secondRate);
183
184             if (fastStateJob == null || fastStateJob.isCancelled()) {
185                 fastStateJob = scheduler.scheduleWithFixedDelay(fastStateRunnable, 0, FAST_STATUS_REFRESH_INTERVAL,
186                         TimeUnit.MILLISECONDS);
187             }
188
189             if (slowStateJob == null || slowStateJob.isCancelled()) {
190                 slowStateJob = scheduler.scheduleWithFixedDelay(slowStateRunnable, 0, SLOW_STATUS_REFRESH_INTERVAL,
191                         TimeUnit.MILLISECONDS);
192             }
193
194             if (enableEvents) {
195                 if (eventThread == null) {
196                     eventThread = new Thread(eventRunnable, "openHAB-Tesla-Events-" + getThing().getUID());
197                     eventThread.start();
198                 }
199             }
200
201         } finally {
202             lock.unlock();
203         }
204     }
205
206     @Override
207     public void dispose() {
208         logger.trace("Disposing the Tesla handler for {}", getThing().getUID());
209         lock.lock();
210         try {
211             if (fastStateJob != null && !fastStateJob.isCancelled()) {
212                 fastStateJob.cancel(true);
213                 fastStateJob = null;
214             }
215
216             if (slowStateJob != null && !slowStateJob.isCancelled()) {
217                 slowStateJob.cancel(true);
218                 slowStateJob = null;
219             }
220
221             if (eventThread != null && !eventThread.isInterrupted()) {
222                 eventThread.interrupt();
223                 eventThread = null;
224             }
225         } finally {
226             lock.unlock();
227         }
228     }
229
230     /**
231      * Retrieves the unique vehicle id this handler is associated with
232      *
233      * @return the vehicle id
234      */
235     public String getVehicleId() {
236         if (vehicle != null) {
237             return vehicle.id;
238         } else {
239             return null;
240         }
241     }
242
243     @Override
244     public void handleCommand(ChannelUID channelUID, Command command) {
245         logger.debug("handleCommand {} {}", channelUID, command);
246         String channelID = channelUID.getId();
247         TeslaChannelSelector selector = TeslaChannelSelector.getValueSelectorFromChannelID(channelID);
248
249         if (command instanceof RefreshType) {
250             if (!isAwake()) {
251                 logger.debug("Waking vehicle to refresh all data");
252                 wakeUp();
253             }
254
255             setActive();
256
257             // Request the state of all known variables. This is sub-optimal, but the requests get scheduled and
258             // throttled so we are safe not to break the Tesla SLA
259             requestAllData();
260         } else {
261             if (selector != null) {
262                 if (!isAwake() && allowWakeUpForCommands) {
263                     logger.debug("Waking vehicle to send command.");
264                     wakeUp();
265                     setActive();
266                 }
267                 try {
268                     switch (selector) {
269                         case CHARGE_LIMIT_SOC: {
270                             if (command instanceof PercentType) {
271                                 setChargeLimit(((PercentType) command).intValue());
272                             } else if (command instanceof OnOffType && command == OnOffType.ON) {
273                                 setChargeLimit(100);
274                             } else if (command instanceof OnOffType && command == OnOffType.OFF) {
275                                 setChargeLimit(0);
276                             } else if (command instanceof IncreaseDecreaseType
277                                     && command == IncreaseDecreaseType.INCREASE) {
278                                 setChargeLimit(Math.min(chargeState.charge_limit_soc + 1, 100));
279                             } else if (command instanceof IncreaseDecreaseType
280                                     && command == IncreaseDecreaseType.DECREASE) {
281                                 setChargeLimit(Math.max(chargeState.charge_limit_soc - 1, 0));
282                             }
283                             break;
284                         }
285                         case CHARGE_AMPS:
286                             Integer amps = null;
287                             if (command instanceof DecimalType) {
288                                 amps = ((DecimalType) command).intValue();
289                             }
290                             if (command instanceof QuantityType<?>) {
291                                 QuantityType<?> qamps = ((QuantityType<?>) command).toUnit(Units.AMPERE);
292                                 if (qamps != null) {
293                                     amps = qamps.intValue();
294                                 }
295                             }
296                             if (amps != null) {
297                                 if (amps < 5 || amps > 32) {
298                                     logger.warn("Charging amps can only be set in a range of 5-32A, but not to {}A.",
299                                             amps);
300                                     return;
301                                 }
302                                 setChargingAmps(amps);
303                             }
304                             break;
305                         case COMBINED_TEMP: {
306                             QuantityType<Temperature> quantity = commandToQuantityType(command);
307                             if (quantity != null) {
308                                 setCombinedTemperature(quanityToRoundedFloat(quantity));
309                             }
310                             break;
311                         }
312                         case DRIVER_TEMP: {
313                             QuantityType<Temperature> quantity = commandToQuantityType(command);
314                             if (quantity != null) {
315                                 setDriverTemperature(quanityToRoundedFloat(quantity));
316                             }
317                             break;
318                         }
319                         case PASSENGER_TEMP: {
320                             QuantityType<Temperature> quantity = commandToQuantityType(command);
321                             if (quantity != null) {
322                                 setPassengerTemperature(quanityToRoundedFloat(quantity));
323                             }
324                             break;
325                         }
326                         case SENTRY_MODE: {
327                             if (command instanceof OnOffType) {
328                                 setSentryMode(command == OnOffType.ON);
329                             }
330                             break;
331                         }
332                         case SUN_ROOF_STATE: {
333                             if (command instanceof StringType) {
334                                 setSunroof(command.toString());
335                             }
336                             break;
337                         }
338                         case CHARGE_TO_MAX: {
339                             if (command instanceof OnOffType) {
340                                 if (((OnOffType) command) == OnOffType.ON) {
341                                     setMaxRangeCharging(true);
342                                 } else {
343                                     setMaxRangeCharging(false);
344                                 }
345                             }
346                             break;
347                         }
348                         case CHARGE: {
349                             if (command instanceof OnOffType) {
350                                 if (((OnOffType) command) == OnOffType.ON) {
351                                     charge(true);
352                                 } else {
353                                     charge(false);
354                                 }
355                             }
356                             break;
357                         }
358                         case FLASH: {
359                             if (command instanceof OnOffType) {
360                                 if (((OnOffType) command) == OnOffType.ON) {
361                                     flashLights();
362                                 }
363                             }
364                             break;
365                         }
366                         case HONK_HORN: {
367                             if (command instanceof OnOffType) {
368                                 if (((OnOffType) command) == OnOffType.ON) {
369                                     honkHorn();
370                                 }
371                             }
372                             break;
373                         }
374                         case CHARGEPORT: {
375                             if (command instanceof OnOffType) {
376                                 if (((OnOffType) command) == OnOffType.ON) {
377                                     openChargePort();
378                                 }
379                             }
380                             break;
381                         }
382                         case DOOR_LOCK: {
383                             if (command instanceof OnOffType) {
384                                 if (((OnOffType) command) == OnOffType.ON) {
385                                     lockDoors(true);
386                                 } else {
387                                     lockDoors(false);
388                                 }
389                             }
390                             break;
391                         }
392                         case AUTO_COND: {
393                             if (command instanceof OnOffType) {
394                                 if (((OnOffType) command) == OnOffType.ON) {
395                                     autoConditioning(true);
396                                 } else {
397                                     autoConditioning(false);
398                                 }
399                             }
400                             break;
401                         }
402                         case WAKEUP: {
403                             if (command instanceof OnOffType) {
404                                 if (((OnOffType) command) == OnOffType.ON) {
405                                     wakeUp();
406                                 }
407                             }
408                             break;
409                         }
410                         case FT: {
411                             if (command instanceof OnOffType) {
412                                 if (((OnOffType) command) == OnOffType.ON) {
413                                     openFrunk();
414                                 }
415                             }
416                             break;
417                         }
418                         case RT: {
419                             if (command instanceof OnOffType) {
420                                 if (((OnOffType) command) == OnOffType.ON) {
421                                     if (vehicleState.rt == 0) {
422                                         openTrunk();
423                                     }
424                                 } else {
425                                     if (vehicleState.rt == 1) {
426                                         closeTrunk();
427                                     }
428                                 }
429                             }
430                             break;
431                         }
432                         case VALET_MODE: {
433                             if (command instanceof OnOffType) {
434                                 int valetpin = ((BigDecimal) getConfig().get(VALETPIN)).intValue();
435                                 if (((OnOffType) command) == OnOffType.ON) {
436                                     setValetMode(true, valetpin);
437                                 } else {
438                                     setValetMode(false, valetpin);
439                                 }
440                             }
441                             break;
442                         }
443                         case RESET_VALET_PIN: {
444                             if (command instanceof OnOffType) {
445                                 if (((OnOffType) command) == OnOffType.ON) {
446                                     resetValetPin();
447                                 }
448                             }
449                             break;
450                         }
451                         default:
452                             break;
453                     }
454                     return;
455                 } catch (IllegalArgumentException e) {
456                     logger.warn(
457                             "An error occurred while trying to set the read-only variable associated with channel '{}' to '{}'",
458                             channelID, command.toString());
459                 }
460             }
461         }
462     }
463
464     public void sendCommand(String command, String payLoad, WebTarget target) {
465         if (command.equals(COMMAND_WAKE_UP) || isAwake() || allowWakeUpForCommands) {
466             Request request = account.newRequest(this, command, payLoad, target, allowWakeUpForCommands);
467             if (stateThrottler != null) {
468                 stateThrottler.submit(COMMAND_THROTTLE, request);
469             }
470         }
471     }
472
473     public void sendCommand(String command) {
474         sendCommand(command, "{}");
475     }
476
477     public void sendCommand(String command, String payLoad) {
478         if (command.equals(COMMAND_WAKE_UP) || isAwake() || allowWakeUpForCommands) {
479             Request request = account.newRequest(this, command, payLoad, account.commandTarget, allowWakeUpForCommands);
480             if (stateThrottler != null) {
481                 stateThrottler.submit(COMMAND_THROTTLE, request);
482             }
483         }
484     }
485
486     public void sendCommand(String command, WebTarget target) {
487         if (command.equals(COMMAND_WAKE_UP) || isAwake() || allowWakeUpForCommands) {
488             Request request = account.newRequest(this, command, "{}", target, allowWakeUpForCommands);
489             if (stateThrottler != null) {
490                 stateThrottler.submit(COMMAND_THROTTLE, request);
491             }
492         }
493     }
494
495     public void requestData(String command, String payLoad) {
496         if (command.equals(COMMAND_WAKE_UP) || isAwake() || allowWakeUpForCommands) {
497             Request request = account.newRequest(this, command, payLoad, account.dataRequestTarget, false);
498             if (stateThrottler != null) {
499                 stateThrottler.submit(DATA_THROTTLE, request);
500             }
501         }
502     }
503
504     @Override
505     protected void updateStatus(ThingStatus status) {
506         super.updateStatus(status);
507     }
508
509     @Override
510     protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
511         super.updateStatus(status, statusDetail);
512     }
513
514     @Override
515     protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
516         super.updateStatus(status, statusDetail, description);
517     }
518
519     public void requestData(String command) {
520         requestData(command, null);
521     }
522
523     public void queryVehicle(String parameter) {
524         WebTarget target = account.vehicleTarget.path(parameter);
525         sendCommand(parameter, null, target);
526     }
527
528     public void requestAllData() {
529         requestData(DRIVE_STATE);
530         requestData(VEHICLE_STATE);
531         requestData(CHARGE_STATE);
532         requestData(CLIMATE_STATE);
533         requestData(GUI_STATE);
534     }
535
536     protected boolean isAwake() {
537         return vehicle != null && "online".equals(vehicle.state) && vehicle.vehicle_id != null;
538     }
539
540     protected boolean isInMotion() {
541         if (driveState != null) {
542             if (driveState.speed != null && driveState.shift_state != null) {
543                 return !"Undefined".equals(driveState.speed)
544                         && (!"P".equals(driveState.shift_state) || !"Undefined".equals(driveState.shift_state));
545             }
546         }
547         return false;
548     }
549
550     protected boolean isInactive() {
551         // vehicle is inactive in case
552         // - it does not charge
553         // - it has not moved or optionally stopped reporting drive state, in the observation period
554         // - it is not in dog, camp, keep, sentry or any other mode that keeps it online
555         return isInactive && !isCharging() && !notReadyForSleep();
556     }
557
558     protected boolean isCharging() {
559         return chargeState != null && "Charging".equals(chargeState.charging_state);
560     }
561
562     protected boolean notReadyForSleep() {
563         boolean status;
564         int computedInactivityPeriod = inactivity;
565
566         if (useAdvancedStates) {
567             if (vehicleState.is_user_present && !isInMotion()) {
568                 logger.debug("Car is occupied but stationary.");
569                 if (lastAdvModesTimestamp < (System.currentTimeMillis()
570                         - (THRESHOLD_INTERVAL_FOR_ADVANCED_MINUTES * 60 * 1000))) {
571                     logger.debug("Ignoring after {} minutes.", THRESHOLD_INTERVAL_FOR_ADVANCED_MINUTES);
572                 } else {
573                     return (backOffCounter++ % 6 == 0); // using 6 should make sure 1 out of 5 pollers get serviced,
574                                                         // about every min.
575                 }
576             } else if (vehicleState.sentry_mode) {
577                 logger.debug("Car is in sentry mode.");
578                 if (lastAdvModesTimestamp < (System.currentTimeMillis()
579                         - (THRESHOLD_INTERVAL_FOR_ADVANCED_MINUTES * 60 * 1000))) {
580                     logger.debug("Ignoring after {} minutes.", THRESHOLD_INTERVAL_FOR_ADVANCED_MINUTES);
581                 } else {
582                     return (backOffCounter++ % 6 == 0);
583                 }
584             } else if ((vehicleState.center_display_state != 0) && (!isInMotion())) {
585                 logger.debug("Car is in camp, climate keep, dog, or other mode preventing sleep. Mode {}",
586                         vehicleState.center_display_state);
587                 return (backOffCounter++ % 6 == 0);
588             } else {
589                 lastAdvModesTimestamp = System.currentTimeMillis();
590             }
591         }
592
593         if (vehicleState.homelink_nearby) {
594             computedInactivityPeriod = MOVE_THRESHOLD_INTERVAL_MINUTES_DEFAULT;
595             logger.debug("Car is at home. Movement or drive state threshold is {} min.",
596                     MOVE_THRESHOLD_INTERVAL_MINUTES_DEFAULT);
597         }
598
599         if (useDriveState) {
600             if (driveState.shift_state != null) {
601                 logger.debug("Car drive state not null and not ready to sleep.");
602                 return true;
603             } else {
604                 status = lastDriveStateChangeToNullTimestamp > (System.currentTimeMillis()
605                         - (computedInactivityPeriod * 60 * 1000));
606                 if (status) {
607                     logger.debug("Drivestate is null but has changed recently, therefore continuing to poll.");
608                     return status;
609                 } else {
610                     logger.debug("Drivestate has changed to null after interval {} min and can now be put to sleep.",
611                             computedInactivityPeriod);
612                     return status;
613                 }
614             }
615         } else {
616             status = lastLocationChangeTimestamp > (System.currentTimeMillis()
617                     - (computedInactivityPeriod * 60 * 1000));
618             if (status) {
619                 logger.debug("Car has moved recently and can not sleep");
620                 return status;
621             } else {
622                 logger.debug("Car has not moved in {} min, and can sleep", computedInactivityPeriod);
623                 return status;
624             }
625         }
626     }
627
628     protected boolean allowQuery() {
629         return (isAwake() && !isInactive());
630     }
631
632     protected void setActive() {
633         isInactive = false;
634         lastLocationChangeTimestamp = System.currentTimeMillis();
635         lastDriveStateChangeToNullTimestamp = System.currentTimeMillis();
636         lastLatitude = 0;
637         lastLongitude = 0;
638     }
639
640     protected boolean checkResponse(Response response, boolean immediatelyFail) {
641         if (response != null && response.getStatus() == 200) {
642             return true;
643         } else if (response != null && response.getStatus() == 401) {
644             logger.debug("The access token has expired, trying to get a new one.");
645             account.authenticate();
646             return false;
647         } else {
648             apiIntervalErrors++;
649             if (immediatelyFail || apiIntervalErrors >= TeslaAccountHandler.API_MAXIMUM_ERRORS_IN_INTERVAL) {
650                 if (immediatelyFail) {
651                     logger.warn("Got an unsuccessful result, setting vehicle to offline and will try again");
652                 } else {
653                     logger.warn("Reached the maximum number of errors ({}) for the current interval ({} seconds)",
654                             TeslaAccountHandler.API_MAXIMUM_ERRORS_IN_INTERVAL,
655                             TeslaAccountHandler.API_ERROR_INTERVAL_SECONDS);
656                 }
657
658                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
659             } else if ((System.currentTimeMillis() - apiIntervalTimestamp) > 1000
660                     * TeslaAccountHandler.API_ERROR_INTERVAL_SECONDS) {
661                 logger.trace("Resetting the error counter. ({} errors in the last interval)", apiIntervalErrors);
662                 apiIntervalTimestamp = System.currentTimeMillis();
663                 apiIntervalErrors = 0;
664             }
665         }
666
667         return false;
668     }
669
670     public void setChargeLimit(int percent) {
671         JsonObject payloadObject = new JsonObject();
672         payloadObject.addProperty("percent", percent);
673         sendCommand(COMMAND_SET_CHARGE_LIMIT, gson.toJson(payloadObject), account.commandTarget);
674         requestData(CHARGE_STATE);
675     }
676
677     public void setChargingAmps(int amps) {
678         JsonObject payloadObject = new JsonObject();
679         payloadObject.addProperty("charging_amps", amps);
680         sendCommand(COMMAND_SET_CHARGING_AMPS, gson.toJson(payloadObject), account.commandTarget);
681         requestData(CHARGE_STATE);
682     }
683
684     public void setSentryMode(boolean b) {
685         JsonObject payloadObject = new JsonObject();
686         payloadObject.addProperty("on", b);
687         sendCommand(COMMAND_SET_SENTRY_MODE, gson.toJson(payloadObject), account.commandTarget);
688         requestData(VEHICLE_STATE);
689     }
690
691     public void setSunroof(String state) {
692         if (state.equals("vent") || state.equals("close")) {
693             JsonObject payloadObject = new JsonObject();
694             payloadObject.addProperty("state", state);
695             sendCommand(COMMAND_SUN_ROOF, gson.toJson(payloadObject), account.commandTarget);
696             requestData(VEHICLE_STATE);
697         } else {
698             logger.warn("Ignoring invalid command '{}' for sunroof.", state);
699         }
700     }
701
702     /**
703      * Sets the driver and passenger temperatures.
704      *
705      * While setting different temperature values is supported by the API, in practice this does not always work
706      * reliably, possibly if the the
707      * only reliable method is to set the driver and passenger temperature to the same value
708      *
709      * @param driverTemperature in Celsius
710      * @param passenegerTemperature in Celsius
711      */
712     public void setTemperature(float driverTemperature, float passenegerTemperature) {
713         JsonObject payloadObject = new JsonObject();
714         payloadObject.addProperty("driver_temp", driverTemperature);
715         payloadObject.addProperty("passenger_temp", passenegerTemperature);
716         sendCommand(COMMAND_SET_TEMP, gson.toJson(payloadObject), account.commandTarget);
717         requestData(CLIMATE_STATE);
718     }
719
720     public void setCombinedTemperature(float temperature) {
721         setTemperature(temperature, temperature);
722     }
723
724     public void setDriverTemperature(float temperature) {
725         setTemperature(temperature, climateState != null ? climateState.passenger_temp_setting : temperature);
726     }
727
728     public void setPassengerTemperature(float temperature) {
729         setTemperature(climateState != null ? climateState.driver_temp_setting : temperature, temperature);
730     }
731
732     public void openFrunk() {
733         JsonObject payloadObject = new JsonObject();
734         payloadObject.addProperty("which_trunk", "front");
735         sendCommand(COMMAND_ACTUATE_TRUNK, gson.toJson(payloadObject), account.commandTarget);
736         requestData(VEHICLE_STATE);
737     }
738
739     public void openTrunk() {
740         JsonObject payloadObject = new JsonObject();
741         payloadObject.addProperty("which_trunk", "rear");
742         sendCommand(COMMAND_ACTUATE_TRUNK, gson.toJson(payloadObject), account.commandTarget);
743         requestData(VEHICLE_STATE);
744     }
745
746     public void closeTrunk() {
747         openTrunk();
748     }
749
750     public void setValetMode(boolean b, Integer pin) {
751         JsonObject payloadObject = new JsonObject();
752         payloadObject.addProperty("on", b);
753         if (pin != null) {
754             payloadObject.addProperty("password", String.format("%04d", pin));
755         }
756         sendCommand(COMMAND_SET_VALET_MODE, gson.toJson(payloadObject), account.commandTarget);
757         requestData(VEHICLE_STATE);
758     }
759
760     public void resetValetPin() {
761         sendCommand(COMMAND_RESET_VALET_PIN, account.commandTarget);
762         requestData(VEHICLE_STATE);
763     }
764
765     public void setMaxRangeCharging(boolean b) {
766         sendCommand(b ? COMMAND_CHARGE_MAX : COMMAND_CHARGE_STD, account.commandTarget);
767         requestData(CHARGE_STATE);
768     }
769
770     public void charge(boolean b) {
771         sendCommand(b ? COMMAND_CHARGE_START : COMMAND_CHARGE_STOP, account.commandTarget);
772         requestData(CHARGE_STATE);
773     }
774
775     public void flashLights() {
776         sendCommand(COMMAND_FLASH_LIGHTS, account.commandTarget);
777     }
778
779     public void honkHorn() {
780         sendCommand(COMMAND_HONK_HORN, account.commandTarget);
781     }
782
783     public void openChargePort() {
784         sendCommand(COMMAND_OPEN_CHARGE_PORT, account.commandTarget);
785         requestData(CHARGE_STATE);
786     }
787
788     public void lockDoors(boolean b) {
789         sendCommand(b ? COMMAND_DOOR_LOCK : COMMAND_DOOR_UNLOCK, account.commandTarget);
790         requestData(VEHICLE_STATE);
791     }
792
793     public void autoConditioning(boolean b) {
794         sendCommand(b ? COMMAND_AUTO_COND_START : COMMAND_AUTO_COND_STOP, account.commandTarget);
795         requestData(CLIMATE_STATE);
796     }
797
798     public void wakeUp() {
799         sendCommand(COMMAND_WAKE_UP, account.wakeUpTarget);
800     }
801
802     protected Vehicle queryVehicle() {
803         String authHeader = account.getAuthHeader();
804
805         if (authHeader != null) {
806             try {
807                 // get a list of vehicles
808                 Response response = account.vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
809                         .header("Authorization", authHeader).get();
810
811                 logger.debug("Querying the vehicle, response : {}, {}", response.getStatus(),
812                         response.getStatusInfo().getReasonPhrase());
813
814                 if (!checkResponse(response, true)) {
815                     logger.debug("An error occurred while querying the vehicle");
816                     return null;
817                 }
818
819                 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
820                 Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
821
822                 for (Vehicle vehicle : vehicleArray) {
823                     logger.debug("Querying the vehicle: VIN {}", vehicle.vin);
824                     if (vehicle.vin.equals(getConfig().get(VIN))) {
825                         vehicleJSON = gson.toJson(vehicle);
826                         parseAndUpdate("queryVehicle", null, vehicleJSON);
827                         if (logger.isTraceEnabled()) {
828                             logger.trace("Vehicle is id {}/vehicle_id {}/tokens {}", vehicle.id, vehicle.vehicle_id,
829                                     vehicle.tokens);
830                         }
831                         return vehicle;
832                     }
833                 }
834             } catch (ProcessingException e) {
835                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
836             }
837         }
838         return null;
839     }
840
841     protected void queryVehicleAndUpdate() {
842         vehicle = queryVehicle();
843     }
844
845     public void parseAndUpdate(String request, String payLoad, String result) {
846         final Double LOCATION_THRESHOLD = .0000001;
847
848         JsonObject jsonObject = null;
849
850         try {
851             if (request != null && result != null && !"null".equals(result)) {
852                 updateStatus(ThingStatus.ONLINE);
853                 // first, update state objects
854                 switch (request) {
855                     case DRIVE_STATE: {
856                         driveState = gson.fromJson(result, DriveState.class);
857
858                         if (Math.abs(lastLatitude - driveState.latitude) > LOCATION_THRESHOLD
859                                 || Math.abs(lastLongitude - driveState.longitude) > LOCATION_THRESHOLD) {
860                             logger.debug("Vehicle moved, resetting last location timestamp");
861
862                             lastLatitude = driveState.latitude;
863                             lastLongitude = driveState.longitude;
864                             lastLocationChangeTimestamp = System.currentTimeMillis();
865                         }
866                         logger.trace("Drive state: {}", driveState.shift_state);
867
868                         if ((driveState.shift_state == null) && (lastValidDriveStateNotNull)) {
869                             logger.debug("Set NULL shiftstate time");
870                             lastValidDriveStateNotNull = false;
871                             lastDriveStateChangeToNullTimestamp = System.currentTimeMillis();
872                         } else if (driveState.shift_state != null) {
873                             logger.trace("Clear NULL shiftstate time");
874                             lastValidDriveStateNotNull = true;
875                         }
876
877                         break;
878                     }
879                     case GUI_STATE: {
880                         guiState = gson.fromJson(result, GUIState.class);
881                         break;
882                     }
883                     case VEHICLE_STATE: {
884                         vehicleState = gson.fromJson(result, VehicleState.class);
885                         break;
886                     }
887                     case CHARGE_STATE: {
888                         chargeState = gson.fromJson(result, ChargeState.class);
889                         if (isCharging()) {
890                             updateState(CHANNEL_CHARGE, OnOffType.ON);
891                         } else {
892                             updateState(CHANNEL_CHARGE, OnOffType.OFF);
893                         }
894
895                         break;
896                     }
897                     case CLIMATE_STATE: {
898                         climateState = gson.fromJson(result, ClimateState.class);
899                         BigDecimal avgtemp = roundBigDecimal(new BigDecimal(
900                                 (climateState.driver_temp_setting + climateState.passenger_temp_setting) / 2.0f));
901                         updateState(CHANNEL_COMBINED_TEMP, new QuantityType<>(avgtemp, SIUnits.CELSIUS));
902                         break;
903                     }
904                     case "queryVehicle": {
905                         if (vehicle != null) {
906                             logger.debug("Vehicle state is {}", vehicle.state);
907                         } else {
908                             logger.debug("Vehicle state is initializing or unknown");
909                             break;
910                         }
911
912                         if (vehicle != null && "asleep".equals(vehicle.state)) {
913                             logger.debug("Vehicle is asleep.");
914                             break;
915                         }
916
917                         if (vehicle != null && !lastState.equals(vehicle.state)) {
918                             lastState = vehicle.state;
919
920                             // in case vehicle changed to awake, refresh all data
921                             if (isAwake()) {
922                                 logger.debug("Vehicle is now awake, updating all data");
923                                 lastLocationChangeTimestamp = System.currentTimeMillis();
924                                 lastDriveStateChangeToNullTimestamp = System.currentTimeMillis();
925                                 requestAllData();
926                             }
927
928                             setActive();
929                         }
930
931                         // reset timestamp if elapsed and set inactive to false
932                         if (isInactive && lastStateTimestamp + (API_SLEEP_INTERVAL_MINUTES * 60 * 1000) < System
933                                 .currentTimeMillis()) {
934                             logger.debug("Vehicle did not fall asleep within sleep period, checking again");
935                             setActive();
936                         } else {
937                             boolean wasInactive = isInactive;
938                             isInactive = !isCharging() && !notReadyForSleep();
939
940                             if (!wasInactive && isInactive) {
941                                 lastStateTimestamp = System.currentTimeMillis();
942                                 logger.debug("Vehicle is inactive");
943                             }
944                         }
945
946                         break;
947                     }
948                 }
949
950                 // secondly, reformat the response string to a JSON compliant
951                 // object for some specific non-JSON compatible requests
952                 switch (request) {
953                     case MOBILE_ENABLED_STATE: {
954                         jsonObject = new JsonObject();
955                         jsonObject.addProperty(MOBILE_ENABLED_STATE, result);
956                         break;
957                     }
958                     default: {
959                         jsonObject = JsonParser.parseString(result).getAsJsonObject();
960                         break;
961                     }
962                 }
963             }
964
965             // process the result
966             if (jsonObject != null && result != null && !"null".equals(result)) {
967                 // deal with responses for "set" commands, which get confirmed
968                 // positively, or negatively, in which case a reason for failure
969                 // is provided
970                 if (jsonObject.get("reason") != null && jsonObject.get("reason").getAsString() != null) {
971                     boolean requestResult = jsonObject.get("result").getAsBoolean();
972                     logger.debug("The request ({}) execution was {}, and reported '{}'", new Object[] { request,
973                             requestResult ? "successful" : "not successful", jsonObject.get("reason").getAsString() });
974                 } else {
975                     Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
976
977                     long resultTimeStamp = 0;
978                     for (Map.Entry<String, JsonElement> entry : entrySet) {
979                         if ("timestamp".equals(entry.getKey())) {
980                             resultTimeStamp = Long.valueOf(entry.getValue().getAsString());
981                             if (logger.isTraceEnabled()) {
982                                 Date date = new Date(resultTimeStamp);
983                                 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
984                                 logger.trace("The request result timestamp is {}", dateFormatter.format(date));
985                             }
986                             break;
987                         }
988                     }
989
990                     try {
991                         lock.lock();
992
993                         boolean proceed = true;
994                         if (resultTimeStamp < lastTimeStamp && request == DRIVE_STATE) {
995                             proceed = false;
996                         }
997
998                         if (proceed) {
999                             for (Map.Entry<String, JsonElement> entry : entrySet) {
1000                                 try {
1001                                     TeslaChannelSelector selector = TeslaChannelSelector
1002                                             .getValueSelectorFromRESTID(entry.getKey());
1003                                     if (!selector.isProperty()) {
1004                                         if (!entry.getValue().isJsonNull()) {
1005                                             updateState(selector.getChannelID(), teslaChannelSelectorProxy.getState(
1006                                                     entry.getValue().getAsString(), selector, editProperties()));
1007                                             if (logger.isTraceEnabled()) {
1008                                                 logger.trace(
1009                                                         "The variable/value pair '{}':'{}' is successfully processed",
1010                                                         entry.getKey(), entry.getValue());
1011                                             }
1012                                         } else {
1013                                             updateState(selector.getChannelID(), UnDefType.UNDEF);
1014                                         }
1015                                     } else {
1016                                         if (!entry.getValue().isJsonNull()) {
1017                                             Map<String, String> properties = editProperties();
1018                                             properties.put(selector.getChannelID(), entry.getValue().getAsString());
1019                                             updateProperties(properties);
1020                                             if (logger.isTraceEnabled()) {
1021                                                 logger.trace(
1022                                                         "The variable/value pair '{}':'{}' is successfully used to set property '{}'",
1023                                                         entry.getKey(), entry.getValue(), selector.getChannelID());
1024                                             }
1025                                         }
1026                                     }
1027                                 } catch (IllegalArgumentException e) {
1028                                     logger.trace("The variable/value pair '{}':'{}' is not (yet) supported",
1029                                             entry.getKey(), entry.getValue());
1030                                 } catch (ClassCastException | IllegalStateException e) {
1031                                     logger.trace("An exception occurred while converting the JSON data : '{}'",
1032                                             e.getMessage(), e);
1033                                 }
1034                             }
1035                         } else {
1036                             logger.warn("The result for request '{}' is discarded due to an out of sync timestamp",
1037                                     request);
1038                         }
1039                     } finally {
1040                         lock.unlock();
1041                     }
1042                 }
1043             }
1044         } catch (Exception p) {
1045             logger.error("An exception occurred while parsing data received from the vehicle: '{}'", p.getMessage());
1046         }
1047     }
1048
1049     @SuppressWarnings("unchecked")
1050     protected QuantityType<Temperature> commandToQuantityType(Command command) {
1051         if (command instanceof QuantityType) {
1052             return ((QuantityType<Temperature>) command).toUnit(SIUnits.CELSIUS);
1053         }
1054         return new QuantityType<>(new BigDecimal(command.toString()), SIUnits.CELSIUS);
1055     }
1056
1057     protected float quanityToRoundedFloat(QuantityType<Temperature> quantity) {
1058         return roundBigDecimal(quantity.toBigDecimal()).floatValue();
1059     }
1060
1061     protected BigDecimal roundBigDecimal(BigDecimal value) {
1062         return value.setScale(1, RoundingMode.HALF_EVEN);
1063     }
1064
1065     protected Runnable slowStateRunnable = () -> {
1066         try {
1067             queryVehicleAndUpdate();
1068             boolean allowQuery = allowQuery();
1069
1070             if (allowQuery) {
1071                 requestData(CHARGE_STATE);
1072                 requestData(CLIMATE_STATE);
1073                 requestData(GUI_STATE);
1074                 queryVehicle(MOBILE_ENABLED_STATE);
1075             } else {
1076                 if (allowWakeUp) {
1077                     wakeUp();
1078                 } else {
1079                     if (isAwake()) {
1080                         logger.debug("slowpoll: Throttled to allow sleep, occupied/idle, or in a console mode");
1081                     } else {
1082                         lastAdvModesTimestamp = System.currentTimeMillis();
1083                     }
1084                 }
1085             }
1086         } catch (Exception e) {
1087             logger.warn("Exception occurred in slowStateRunnable", e);
1088         }
1089     };
1090
1091     protected Runnable fastStateRunnable = () -> {
1092         if (getThing().getStatus() == ThingStatus.ONLINE) {
1093             boolean allowQuery = allowQuery();
1094
1095             if (allowQuery) {
1096                 requestData(DRIVE_STATE);
1097                 requestData(VEHICLE_STATE);
1098             } else {
1099                 if (allowWakeUp) {
1100                     wakeUp();
1101                 } else {
1102                     if (isAwake()) {
1103                         logger.debug("fastpoll: Throttled to allow sleep, occupied/idle, or in a console mode");
1104                     }
1105                 }
1106             }
1107         }
1108     };
1109
1110     protected Runnable eventRunnable = new Runnable() {
1111         TeslaEventEndpoint eventEndpoint;
1112         boolean isAuthenticated = false;
1113         long lastPingTimestamp = 0;
1114
1115         @Override
1116         public void run() {
1117             eventEndpoint = new TeslaEventEndpoint(webSocketFactory);
1118             eventEndpoint.addEventHandler(new TeslaEventEndpoint.EventHandler() {
1119                 @Override
1120                 public void handleEvent(Event event) {
1121                     if (event != null) {
1122                         switch (event.msg_type) {
1123                             case "control:hello":
1124                                 logger.debug("Event : Received hello");
1125                                 break;
1126                             case "data:update":
1127                                 logger.debug("Event : Received an update: '{}'", event.value);
1128
1129                                 String vals[] = event.value.split(",");
1130                                 long currentTimeStamp = Long.valueOf(vals[0]);
1131                                 long systemTimeStamp = System.currentTimeMillis();
1132                                 if (logger.isDebugEnabled()) {
1133                                     SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
1134                                     logger.debug("STS {} CTS {} Delta {}",
1135                                             dateFormatter.format(new Date(systemTimeStamp)),
1136                                             dateFormatter.format(new Date(currentTimeStamp)),
1137                                             systemTimeStamp - currentTimeStamp);
1138                                 }
1139                                 if (systemTimeStamp - currentTimeStamp < EVENT_TIMESTAMP_AGE_LIMIT) {
1140                                     if (currentTimeStamp > lastTimeStamp) {
1141                                         lastTimeStamp = Long.valueOf(vals[0]);
1142                                         if (logger.isDebugEnabled()) {
1143                                             SimpleDateFormat dateFormatter = new SimpleDateFormat(
1144                                                     "yyyy-MM-dd'T'HH:mm:ss.SSS");
1145                                             logger.debug("Event : Event stamp is {}",
1146                                                     dateFormatter.format(new Date(lastTimeStamp)));
1147                                         }
1148                                         for (int i = 0; i < EventKeys.values().length; i++) {
1149                                             TeslaChannelSelector selector = TeslaChannelSelector
1150                                                     .getValueSelectorFromRESTID((EventKeys.values()[i]).toString());
1151
1152                                             if (!selector.isProperty()) {
1153                                                 State newState = teslaChannelSelectorProxy.getState(vals[i], selector,
1154                                                         editProperties());
1155                                                 if (newState != null && !"".equals(vals[i])) {
1156                                                     updateState(selector.getChannelID(), newState);
1157                                                 } else {
1158                                                     updateState(selector.getChannelID(), UnDefType.UNDEF);
1159                                                 }
1160                                                 if (logger.isTraceEnabled()) {
1161                                                     logger.trace(
1162                                                             "The variable/value pair '{}':'{}' is successfully processed",
1163                                                             EventKeys.values()[i], vals[i]);
1164                                                 }
1165                                             } else {
1166                                                 Map<String, String> properties = editProperties();
1167                                                 properties.put(selector.getChannelID(),
1168                                                         (selector.getState(vals[i])).toString());
1169                                                 updateProperties(properties);
1170                                                 if (logger.isTraceEnabled()) {
1171                                                     logger.trace(
1172                                                             "The variable/value pair '{}':'{}' is successfully used to set property '{}'",
1173                                                             EventKeys.values()[i], vals[i], selector.getChannelID());
1174                                                 }
1175                                             }
1176                                         }
1177                                     } else {
1178                                         if (logger.isDebugEnabled()) {
1179                                             SimpleDateFormat dateFormatter = new SimpleDateFormat(
1180                                                     "yyyy-MM-dd'T'HH:mm:ss.SSS");
1181                                             logger.debug(
1182                                                     "Event : Discarding an event with an out of sync timestamp {} (last is {})",
1183                                                     dateFormatter.format(new Date(currentTimeStamp)),
1184                                                     dateFormatter.format(new Date(lastTimeStamp)));
1185                                         }
1186                                     }
1187                                 } else {
1188                                     if (logger.isDebugEnabled()) {
1189                                         SimpleDateFormat dateFormatter = new SimpleDateFormat(
1190                                                 "yyyy-MM-dd'T'HH:mm:ss.SSS");
1191                                         logger.debug(
1192                                                 "Event : Discarding an event that differs {} ms from the system time: {} (system is {})",
1193                                                 systemTimeStamp - currentTimeStamp,
1194                                                 dateFormatter.format(currentTimeStamp),
1195                                                 dateFormatter.format(systemTimeStamp));
1196                                     }
1197                                     if (systemTimeStamp - currentTimeStamp > EVENT_TIMESTAMP_MAX_DELTA) {
1198                                         logger.trace("Event : The event endpoint will be reset");
1199                                         eventEndpoint.close();
1200                                     }
1201                                 }
1202                                 break;
1203                             case "data:error":
1204                                 logger.debug("Event : Received an error: '{}'/'{}'", event.value, event.error_type);
1205                                 eventEndpoint.close();
1206                                 break;
1207                         }
1208                     }
1209                 }
1210             });
1211
1212             while (true) {
1213                 try {
1214                     if (getThing().getStatus() == ThingStatus.ONLINE) {
1215                         if (isAwake()) {
1216                             eventEndpoint.connect(new URI(URI_EVENT));
1217
1218                             if (eventEndpoint.isConnected()) {
1219                                 if (!isAuthenticated) {
1220                                     logger.debug("Event : Authenticating vehicle {}", vehicle.vehicle_id);
1221                                     JsonObject payloadObject = new JsonObject();
1222                                     payloadObject.addProperty("msg_type", "data:subscribe_oauth");
1223                                     payloadObject.addProperty("token", account.getAccessToken());
1224                                     payloadObject.addProperty("value", Arrays.asList(EventKeys.values()).stream()
1225                                             .skip(1).map(Enum::toString).collect(Collectors.joining(",")));
1226                                     payloadObject.addProperty("tag", vehicle.vehicle_id);
1227
1228                                     eventEndpoint.sendMessage(gson.toJson(payloadObject));
1229                                     isAuthenticated = true;
1230
1231                                     lastPingTimestamp = System.nanoTime();
1232                                 }
1233
1234                                 if (TimeUnit.MILLISECONDS.convert(System.nanoTime() - lastPingTimestamp,
1235                                         TimeUnit.NANOSECONDS) > EVENT_PING_INTERVAL) {
1236                                     logger.trace("Event : Pinging the Tesla event stream infrastructure");
1237                                     eventEndpoint.ping();
1238                                     lastPingTimestamp = System.nanoTime();
1239                                 }
1240                             }
1241
1242                             if (!eventEndpoint.isConnected()) {
1243                                 isAuthenticated = false;
1244                                 eventIntervalErrors++;
1245                                 if (eventIntervalErrors >= EVENT_MAXIMUM_ERRORS_IN_INTERVAL) {
1246                                     logger.warn(
1247                                             "Event : Reached the maximum number of errors ({}) for the current interval ({} seconds)",
1248                                             EVENT_MAXIMUM_ERRORS_IN_INTERVAL, EVENT_ERROR_INTERVAL_SECONDS);
1249                                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
1250                                     eventEndpoint.close();
1251                                 }
1252
1253                                 if ((System.currentTimeMillis() - eventIntervalTimestamp) > 1000
1254                                         * EVENT_ERROR_INTERVAL_SECONDS) {
1255                                     logger.trace(
1256                                             "Event : Resetting the error counter. ({} errors in the last interval)",
1257                                             eventIntervalErrors);
1258                                     eventIntervalTimestamp = System.currentTimeMillis();
1259                                     eventIntervalErrors = 0;
1260                                 }
1261                             }
1262                         } else {
1263                             logger.debug("Event : The vehicle is not awake");
1264                             if (vehicle != null) {
1265                                 if (allowWakeUp) {
1266                                     // wake up the vehicle until streaming token <> 0
1267                                     logger.debug("Event : Waking up the vehicle");
1268                                     wakeUp();
1269                                 }
1270                             } else {
1271                                 vehicle = queryVehicle();
1272                             }
1273                         }
1274                     }
1275                 } catch (URISyntaxException | NumberFormatException | IOException e) {
1276                     logger.debug("Event : An exception occurred while processing events: '{}'", e.getMessage());
1277                 }
1278
1279                 try {
1280                     Thread.sleep(EVENT_STREAM_PAUSE);
1281                 } catch (InterruptedException e) {
1282                     logger.debug("Event : An exception occurred while putting the event thread to sleep: '{}'",
1283                             e.getMessage());
1284                 }
1285
1286                 if (Thread.interrupted()) {
1287                     logger.debug("Event : The event thread was interrupted");
1288                     return;
1289                 }
1290             }
1291         }
1292     };
1293 }