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