2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.tesla.internal.handler;
15 import static org.openhab.binding.tesla.internal.TeslaBindingConstants.*;
17 import java.io.IOException;
18 import java.math.BigDecimal;
19 import java.math.RoundingMode;
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;
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;
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;
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;
75 import com.google.gson.Gson;
76 import com.google.gson.JsonElement;
77 import com.google.gson.JsonObject;
78 import com.google.gson.JsonParser;
81 * The {@link TeslaVehicleHandler} is responsible for handling commands, which are sent
82 * to one of the channels of a specific vehicle.
84 * @author Karel Goderis - Initial contribution
85 * @author Kai Kreuzer - Refactored to use separate account handler and improved configuration options
87 public class TeslaVehicleHandler extends BaseThingHandler {
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;
101 private final Logger logger = LoggerFactory.getLogger(TeslaVehicleHandler.class);
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;
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;
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;
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;
135 protected String lastState = "";
136 protected boolean isInactive = false;
138 protected TeslaAccountHandler account;
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;
147 private final Gson gson = new Gson();
149 public TeslaVehicleHandler(Thing thing, WebSocketFactory webSocketFactory) {
151 this.webSocketFactory = webSocketFactory;
154 @SuppressWarnings("null")
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;
169 account = (TeslaAccountHandler) getBridge().getHandler();
170 lock = new ReentrantLock();
171 scheduler.execute(() -> queryVehicleAndUpdate());
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));
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);
184 if (fastStateJob == null || fastStateJob.isCancelled()) {
185 fastStateJob = scheduler.scheduleWithFixedDelay(fastStateRunnable, 0, FAST_STATUS_REFRESH_INTERVAL,
186 TimeUnit.MILLISECONDS);
189 if (slowStateJob == null || slowStateJob.isCancelled()) {
190 slowStateJob = scheduler.scheduleWithFixedDelay(slowStateRunnable, 0, SLOW_STATUS_REFRESH_INTERVAL,
191 TimeUnit.MILLISECONDS);
195 if (eventThread == null) {
196 eventThread = new Thread(eventRunnable, "openHAB-Tesla-Events-" + getThing().getUID());
207 public void dispose() {
208 logger.trace("Disposing the Tesla handler for {}", getThing().getUID());
211 if (fastStateJob != null && !fastStateJob.isCancelled()) {
212 fastStateJob.cancel(true);
216 if (slowStateJob != null && !slowStateJob.isCancelled()) {
217 slowStateJob.cancel(true);
221 if (eventThread != null && !eventThread.isInterrupted()) {
222 eventThread.interrupt();
231 * Retrieves the unique vehicle id this handler is associated with
233 * @return the vehicle id
235 public String getVehicleId() {
236 if (vehicle != null) {
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);
249 if (command instanceof RefreshType) {
251 logger.debug("Waking vehicle to refresh all data");
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
261 if (selector != null) {
262 if (!isAwake() && allowWakeUpForCommands) {
263 logger.debug("Waking vehicle to send command.");
269 case CHARGE_LIMIT_SOC: {
270 if (command instanceof PercentType) {
271 setChargeLimit(((PercentType) command).intValue());
272 } else if (command instanceof OnOffType && command == OnOffType.ON) {
274 } else if (command instanceof OnOffType && command == OnOffType.OFF) {
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));
287 if (command instanceof DecimalType) {
288 amps = ((DecimalType) command).intValue();
290 if (command instanceof QuantityType<?>) {
291 QuantityType<?> qamps = ((QuantityType<?>) command).toUnit(Units.AMPERE);
293 amps = qamps.intValue();
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.",
302 setChargingAmps(amps);
305 case COMBINED_TEMP: {
306 QuantityType<Temperature> quantity = commandToQuantityType(command);
307 if (quantity != null) {
308 setCombinedTemperature(quanityToRoundedFloat(quantity));
313 QuantityType<Temperature> quantity = commandToQuantityType(command);
314 if (quantity != null) {
315 setDriverTemperature(quanityToRoundedFloat(quantity));
319 case PASSENGER_TEMP: {
320 QuantityType<Temperature> quantity = commandToQuantityType(command);
321 if (quantity != null) {
322 setPassengerTemperature(quanityToRoundedFloat(quantity));
327 if (command instanceof OnOffType) {
328 setSentryMode(command == OnOffType.ON);
332 case SUN_ROOF_STATE: {
333 if (command instanceof StringType) {
334 setSunroof(command.toString());
338 case CHARGE_TO_MAX: {
339 if (command instanceof OnOffType) {
340 if (((OnOffType) command) == OnOffType.ON) {
341 setMaxRangeCharging(true);
343 setMaxRangeCharging(false);
349 if (command instanceof OnOffType) {
350 if (((OnOffType) command) == OnOffType.ON) {
359 if (command instanceof OnOffType) {
360 if (((OnOffType) command) == OnOffType.ON) {
367 if (command instanceof OnOffType) {
368 if (((OnOffType) command) == OnOffType.ON) {
375 if (command instanceof OnOffType) {
376 if (((OnOffType) command) == OnOffType.ON) {
383 if (command instanceof OnOffType) {
384 if (((OnOffType) command) == OnOffType.ON) {
393 if (command instanceof OnOffType) {
394 if (((OnOffType) command) == OnOffType.ON) {
395 autoConditioning(true);
397 autoConditioning(false);
403 if (command instanceof OnOffType) {
404 if (((OnOffType) command) == OnOffType.ON) {
411 if (command instanceof OnOffType) {
412 if (((OnOffType) command) == OnOffType.ON) {
419 if (command instanceof OnOffType) {
420 if (((OnOffType) command) == OnOffType.ON) {
421 if (vehicleState.rt == 0) {
425 if (vehicleState.rt == 1) {
433 if (command instanceof OnOffType) {
434 int valetpin = ((BigDecimal) getConfig().get(VALETPIN)).intValue();
435 if (((OnOffType) command) == OnOffType.ON) {
436 setValetMode(true, valetpin);
438 setValetMode(false, valetpin);
443 case RESET_VALET_PIN: {
444 if (command instanceof OnOffType) {
445 if (((OnOffType) command) == OnOffType.ON) {
455 } catch (IllegalArgumentException e) {
457 "An error occurred while trying to set the read-only variable associated with channel '{}' to '{}'",
458 channelID, command.toString());
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);
473 public void sendCommand(String command) {
474 sendCommand(command, "{}");
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);
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);
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);
505 protected void updateStatus(ThingStatus status) {
506 super.updateStatus(status);
510 protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
511 super.updateStatus(status, statusDetail);
515 protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
516 super.updateStatus(status, statusDetail, description);
519 public void requestData(String command) {
520 requestData(command, null);
523 public void queryVehicle(String parameter) {
524 WebTarget target = account.vehicleTarget.path(parameter);
525 sendCommand(parameter, null, target);
528 public void requestAllData() {
529 requestData(DRIVE_STATE);
530 requestData(VEHICLE_STATE);
531 requestData(CHARGE_STATE);
532 requestData(CLIMATE_STATE);
533 requestData(GUI_STATE);
536 protected boolean isAwake() {
537 return vehicle != null && "online".equals(vehicle.state) && vehicle.vehicle_id != null;
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));
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();
558 protected boolean isCharging() {
559 return chargeState != null && "Charging".equals(chargeState.charging_state);
562 protected boolean notReadyForSleep() {
564 int computedInactivityPeriod = inactivity;
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);
573 return (backOffCounter++ % 6 == 0); // using 6 should make sure 1 out of 5 pollers get serviced,
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);
582 return (backOffCounter++ % 6 == 0);
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);
589 lastAdvModesTimestamp = System.currentTimeMillis();
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);
600 if (driveState.shift_state != null) {
601 logger.debug("Car drive state not null and not ready to sleep.");
604 status = lastDriveStateChangeToNullTimestamp > (System.currentTimeMillis()
605 - (computedInactivityPeriod * 60 * 1000));
607 logger.debug("Drivestate is null but has changed recently, therefore continuing to poll.");
610 logger.debug("Drivestate has changed to null after interval {} min and can now be put to sleep.",
611 computedInactivityPeriod);
616 status = lastLocationChangeTimestamp > (System.currentTimeMillis()
617 - (computedInactivityPeriod * 60 * 1000));
619 logger.debug("Car has moved recently and can not sleep");
622 logger.debug("Car has not moved in {} min, and can sleep", computedInactivityPeriod);
628 protected boolean allowQuery() {
629 return (isAwake() && !isInactive());
632 protected void setActive() {
634 lastLocationChangeTimestamp = System.currentTimeMillis();
635 lastDriveStateChangeToNullTimestamp = System.currentTimeMillis();
640 protected boolean checkResponse(Response response, boolean immediatelyFail) {
641 if (response != null && response.getStatus() == 200) {
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();
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");
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);
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;
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);
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);
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);
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);
698 logger.warn("Ignoring invalid command '{}' for sunroof.", state);
703 * Sets the driver and passenger temperatures.
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
709 * @param driverTemperature in Celsius
710 * @param passenegerTemperature in Celsius
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);
720 public void setCombinedTemperature(float temperature) {
721 setTemperature(temperature, temperature);
724 public void setDriverTemperature(float temperature) {
725 setTemperature(temperature, climateState != null ? climateState.passenger_temp_setting : temperature);
728 public void setPassengerTemperature(float temperature) {
729 setTemperature(climateState != null ? climateState.driver_temp_setting : temperature, temperature);
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);
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);
746 public void closeTrunk() {
750 public void setValetMode(boolean b, Integer pin) {
751 JsonObject payloadObject = new JsonObject();
752 payloadObject.addProperty("on", b);
754 payloadObject.addProperty("password", String.format("%04d", pin));
756 sendCommand(COMMAND_SET_VALET_MODE, gson.toJson(payloadObject), account.commandTarget);
757 requestData(VEHICLE_STATE);
760 public void resetValetPin() {
761 sendCommand(COMMAND_RESET_VALET_PIN, account.commandTarget);
762 requestData(VEHICLE_STATE);
765 public void setMaxRangeCharging(boolean b) {
766 sendCommand(b ? COMMAND_CHARGE_MAX : COMMAND_CHARGE_STD, account.commandTarget);
767 requestData(CHARGE_STATE);
770 public void charge(boolean b) {
771 sendCommand(b ? COMMAND_CHARGE_START : COMMAND_CHARGE_STOP, account.commandTarget);
772 requestData(CHARGE_STATE);
775 public void flashLights() {
776 sendCommand(COMMAND_FLASH_LIGHTS, account.commandTarget);
779 public void honkHorn() {
780 sendCommand(COMMAND_HONK_HORN, account.commandTarget);
783 public void openChargePort() {
784 sendCommand(COMMAND_OPEN_CHARGE_PORT, account.commandTarget);
785 requestData(CHARGE_STATE);
788 public void lockDoors(boolean b) {
789 sendCommand(b ? COMMAND_DOOR_LOCK : COMMAND_DOOR_UNLOCK, account.commandTarget);
790 requestData(VEHICLE_STATE);
793 public void autoConditioning(boolean b) {
794 sendCommand(b ? COMMAND_AUTO_COND_START : COMMAND_AUTO_COND_STOP, account.commandTarget);
795 requestData(CLIMATE_STATE);
798 public void wakeUp() {
799 sendCommand(COMMAND_WAKE_UP, account.wakeUpTarget);
802 protected Vehicle queryVehicle() {
803 String authHeader = account.getAuthHeader();
805 if (authHeader != null) {
807 // get a list of vehicles
808 Response response = account.vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
809 .header("Authorization", authHeader).get();
811 logger.debug("Querying the vehicle, response : {}, {}", response.getStatus(),
812 response.getStatusInfo().getReasonPhrase());
814 if (!checkResponse(response, true)) {
815 logger.debug("An error occurred while querying the vehicle");
819 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
820 Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
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,
834 } catch (ProcessingException e) {
835 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
841 protected void queryVehicleAndUpdate() {
842 vehicle = queryVehicle();
845 public void parseAndUpdate(String request, String payLoad, String result) {
846 final Double LOCATION_THRESHOLD = .0000001;
848 JsonObject jsonObject = null;
851 if (request != null && result != null && !"null".equals(result)) {
852 updateStatus(ThingStatus.ONLINE);
853 // first, update state objects
856 driveState = gson.fromJson(result, DriveState.class);
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");
862 lastLatitude = driveState.latitude;
863 lastLongitude = driveState.longitude;
864 lastLocationChangeTimestamp = System.currentTimeMillis();
866 logger.trace("Drive state: {}", driveState.shift_state);
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;
880 guiState = gson.fromJson(result, GUIState.class);
883 case VEHICLE_STATE: {
884 vehicleState = gson.fromJson(result, VehicleState.class);
888 chargeState = gson.fromJson(result, ChargeState.class);
890 updateState(CHANNEL_CHARGE, OnOffType.ON);
892 updateState(CHANNEL_CHARGE, OnOffType.OFF);
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));
904 case "queryVehicle": {
905 if (vehicle != null) {
906 logger.debug("Vehicle state is {}", vehicle.state);
908 logger.debug("Vehicle state is initializing or unknown");
912 if (vehicle != null && "asleep".equals(vehicle.state)) {
913 logger.debug("Vehicle is asleep.");
917 if (vehicle != null && !lastState.equals(vehicle.state)) {
918 lastState = vehicle.state;
920 // in case vehicle changed to awake, refresh all data
922 logger.debug("Vehicle is now awake, updating all data");
923 lastLocationChangeTimestamp = System.currentTimeMillis();
924 lastDriveStateChangeToNullTimestamp = System.currentTimeMillis();
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");
937 boolean wasInactive = isInactive;
938 isInactive = !isCharging() && !notReadyForSleep();
940 if (!wasInactive && isInactive) {
941 lastStateTimestamp = System.currentTimeMillis();
942 logger.debug("Vehicle is inactive");
950 // secondly, reformat the response string to a JSON compliant
951 // object for some specific non-JSON compatible requests
953 case MOBILE_ENABLED_STATE: {
954 jsonObject = new JsonObject();
955 jsonObject.addProperty(MOBILE_ENABLED_STATE, result);
959 jsonObject = JsonParser.parseString(result).getAsJsonObject();
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
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() });
975 Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
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));
993 boolean proceed = true;
994 if (resultTimeStamp < lastTimeStamp && request == DRIVE_STATE) {
999 for (Map.Entry<String, JsonElement> entry : entrySet) {
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()) {
1009 "The variable/value pair '{}':'{}' is successfully processed",
1010 entry.getKey(), entry.getValue());
1013 updateState(selector.getChannelID(), UnDefType.UNDEF);
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()) {
1022 "The variable/value pair '{}':'{}' is successfully used to set property '{}'",
1023 entry.getKey(), entry.getValue(), selector.getChannelID());
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 : '{}'",
1036 logger.warn("The result for request '{}' is discarded due to an out of sync timestamp",
1044 } catch (Exception p) {
1045 logger.error("An exception occurred while parsing data received from the vehicle: '{}'", p.getMessage());
1049 @SuppressWarnings("unchecked")
1050 protected QuantityType<Temperature> commandToQuantityType(Command command) {
1051 if (command instanceof QuantityType) {
1052 return ((QuantityType<Temperature>) command).toUnit(SIUnits.CELSIUS);
1054 return new QuantityType<>(new BigDecimal(command.toString()), SIUnits.CELSIUS);
1057 protected float quanityToRoundedFloat(QuantityType<Temperature> quantity) {
1058 return roundBigDecimal(quantity.toBigDecimal()).floatValue();
1061 protected BigDecimal roundBigDecimal(BigDecimal value) {
1062 return value.setScale(1, RoundingMode.HALF_EVEN);
1065 protected Runnable slowStateRunnable = () -> {
1067 queryVehicleAndUpdate();
1068 boolean allowQuery = allowQuery();
1071 requestData(CHARGE_STATE);
1072 requestData(CLIMATE_STATE);
1073 requestData(GUI_STATE);
1074 queryVehicle(MOBILE_ENABLED_STATE);
1080 logger.debug("slowpoll: Throttled to allow sleep, occupied/idle, or in a console mode");
1082 lastAdvModesTimestamp = System.currentTimeMillis();
1086 } catch (Exception e) {
1087 logger.warn("Exception occurred in slowStateRunnable", e);
1091 protected Runnable fastStateRunnable = () -> {
1092 if (getThing().getStatus() == ThingStatus.ONLINE) {
1093 boolean allowQuery = allowQuery();
1096 requestData(DRIVE_STATE);
1097 requestData(VEHICLE_STATE);
1103 logger.debug("fastpoll: Throttled to allow sleep, occupied/idle, or in a console mode");
1110 protected Runnable eventRunnable = new Runnable() {
1111 TeslaEventEndpoint eventEndpoint;
1112 boolean isAuthenticated = false;
1113 long lastPingTimestamp = 0;
1117 eventEndpoint = new TeslaEventEndpoint(webSocketFactory);
1118 eventEndpoint.addEventHandler(new TeslaEventEndpoint.EventHandler() {
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");
1127 logger.debug("Event : Received an update: '{}'", event.value);
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);
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)));
1148 for (int i = 0; i < EventKeys.values().length; i++) {
1149 TeslaChannelSelector selector = TeslaChannelSelector
1150 .getValueSelectorFromRESTID((EventKeys.values()[i]).toString());
1152 if (!selector.isProperty()) {
1153 State newState = teslaChannelSelectorProxy.getState(vals[i], selector,
1155 if (newState != null && !"".equals(vals[i])) {
1156 updateState(selector.getChannelID(), newState);
1158 updateState(selector.getChannelID(), UnDefType.UNDEF);
1160 if (logger.isTraceEnabled()) {
1162 "The variable/value pair '{}':'{}' is successfully processed",
1163 EventKeys.values()[i], vals[i]);
1166 Map<String, String> properties = editProperties();
1167 properties.put(selector.getChannelID(),
1168 (selector.getState(vals[i])).toString());
1169 updateProperties(properties);
1170 if (logger.isTraceEnabled()) {
1172 "The variable/value pair '{}':'{}' is successfully used to set property '{}'",
1173 EventKeys.values()[i], vals[i], selector.getChannelID());
1178 if (logger.isDebugEnabled()) {
1179 SimpleDateFormat dateFormatter = new SimpleDateFormat(
1180 "yyyy-MM-dd'T'HH:mm:ss.SSS");
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)));
1188 if (logger.isDebugEnabled()) {
1189 SimpleDateFormat dateFormatter = new SimpleDateFormat(
1190 "yyyy-MM-dd'T'HH:mm:ss.SSS");
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));
1197 if (systemTimeStamp - currentTimeStamp > EVENT_TIMESTAMP_MAX_DELTA) {
1198 logger.trace("Event : The event endpoint will be reset");
1199 eventEndpoint.close();
1204 logger.debug("Event : Received an error: '{}'/'{}'", event.value, event.error_type);
1205 eventEndpoint.close();
1214 if (getThing().getStatus() == ThingStatus.ONLINE) {
1216 eventEndpoint.connect(new URI(URI_EVENT));
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);
1228 eventEndpoint.sendMessage(gson.toJson(payloadObject));
1229 isAuthenticated = true;
1231 lastPingTimestamp = System.nanoTime();
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();
1242 if (!eventEndpoint.isConnected()) {
1243 isAuthenticated = false;
1244 eventIntervalErrors++;
1245 if (eventIntervalErrors >= EVENT_MAXIMUM_ERRORS_IN_INTERVAL) {
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();
1253 if ((System.currentTimeMillis() - eventIntervalTimestamp) > 1000
1254 * EVENT_ERROR_INTERVAL_SECONDS) {
1256 "Event : Resetting the error counter. ({} errors in the last interval)",
1257 eventIntervalErrors);
1258 eventIntervalTimestamp = System.currentTimeMillis();
1259 eventIntervalErrors = 0;
1263 logger.debug("Event : The vehicle is not awake");
1264 if (vehicle != null) {
1266 // wake up the vehicle until streaming token <> 0
1267 logger.debug("Event : Waking up the vehicle");
1271 vehicle = queryVehicle();
1275 } catch (URISyntaxException | NumberFormatException | IOException e) {
1276 logger.debug("Event : An exception occurred while processing events: '{}'", e.getMessage());
1280 Thread.sleep(EVENT_STREAM_PAUSE);
1281 } catch (InterruptedException e) {
1282 logger.debug("Event : An exception occurred while putting the event thread to sleep: '{}'",
1286 if (Thread.interrupted()) {
1287 logger.debug("Event : The event thread was interrupted");