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.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;
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;
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;
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;
77 import com.google.gson.Gson;
78 import com.google.gson.JsonElement;
79 import com.google.gson.JsonObject;
80 import com.google.gson.JsonParser;
83 * The {@link TeslaVehicleHandler} is responsible for handling commands, which are sent
84 * to one of the channels of a specific vehicle.
86 * @author Karel Goderis - Initial contribution
87 * @author Kai Kreuzer - Refactored to use separate account handler and improved configuration options
89 public class TeslaVehicleHandler extends BaseThingHandler {
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;
101 private final Logger logger = LoggerFactory.getLogger(TeslaVehicleHandler.class);
103 protected WebTarget eventTarget;
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;
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;
123 protected double lastLongitude;
124 protected double lastLatitude;
125 protected long lastLocationChangeTimestamp;
127 protected long lastStateTimestamp = System.currentTimeMillis();
128 protected String lastState = "";
129 protected boolean isInactive = false;
131 protected TeslaAccountHandler account;
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;
141 private final Gson gson = new Gson();
143 public TeslaVehicleHandler(Thing thing, ClientBuilder clientBuilder) {
145 this.clientBuilder = clientBuilder;
148 @SuppressWarnings("null")
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);
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);
158 account = (TeslaAccountHandler) getBridge().getHandler();
159 lock = new ReentrantLock();
160 scheduler.execute(() -> queryVehicleAndUpdate());
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));
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);
173 if (fastStateJob == null || fastStateJob.isCancelled()) {
174 fastStateJob = scheduler.scheduleWithFixedDelay(fastStateRunnable, 0, FAST_STATUS_REFRESH_INTERVAL,
175 TimeUnit.MILLISECONDS);
178 if (slowStateJob == null || slowStateJob.isCancelled()) {
179 slowStateJob = scheduler.scheduleWithFixedDelay(slowStateRunnable, 0, SLOW_STATUS_REFRESH_INTERVAL,
180 TimeUnit.MILLISECONDS);
187 if (eventThread == null) {
188 eventThread = new Thread(eventRunnable, "openHAB-Tesla-Events-" + getThing().getUID());
195 public void dispose() {
196 logger.trace("Disposing the Tesla handler for {}", getThing().getUID());
199 if (fastStateJob != null && !fastStateJob.isCancelled()) {
200 fastStateJob.cancel(true);
204 if (slowStateJob != null && !slowStateJob.isCancelled()) {
205 slowStateJob.cancel(true);
209 if (eventThread != null && !eventThread.isInterrupted()) {
210 eventThread.interrupt();
217 if (eventClient != null) {
223 * Retrieves the unique vehicle id this handler is associated with
225 * @return the vehicle id
227 public String getVehicleId() {
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);
237 if (command instanceof RefreshType) {
239 logger.debug("Waking vehicle to refresh all data");
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
249 if (selector != null) {
252 case CHARGE_LIMIT_SOC: {
253 if (command instanceof PercentType) {
254 setChargeLimit(((PercentType) command).intValue());
255 } else if (command instanceof OnOffType && command == OnOffType.ON) {
257 } else if (command instanceof OnOffType && command == OnOffType.OFF) {
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));
270 if (command instanceof DecimalType) {
271 amps = ((DecimalType) command).intValue();
273 if (command instanceof QuantityType<?>) {
274 QuantityType<?> qamps = ((QuantityType<?>) command).toUnit(Units.AMPERE);
276 amps = qamps.intValue();
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.",
285 setChargingAmps(amps);
288 case COMBINED_TEMP: {
289 QuantityType<Temperature> quantity = commandToQuantityType(command);
290 if (quantity != null) {
291 setCombinedTemperature(quanityToRoundedFloat(quantity));
296 QuantityType<Temperature> quantity = commandToQuantityType(command);
297 if (quantity != null) {
298 setDriverTemperature(quanityToRoundedFloat(quantity));
302 case PASSENGER_TEMP: {
303 QuantityType<Temperature> quantity = commandToQuantityType(command);
304 if (quantity != null) {
305 setPassengerTemperature(quanityToRoundedFloat(quantity));
310 if (command instanceof OnOffType) {
311 setSentryMode(command == OnOffType.ON);
315 case SUN_ROOF_STATE: {
316 if (command instanceof StringType) {
317 setSunroof(command.toString());
321 case CHARGE_TO_MAX: {
322 if (command instanceof OnOffType) {
323 if (((OnOffType) command) == OnOffType.ON) {
324 setMaxRangeCharging(true);
326 setMaxRangeCharging(false);
332 if (command instanceof OnOffType) {
333 if (((OnOffType) command) == OnOffType.ON) {
342 if (command instanceof OnOffType) {
343 if (((OnOffType) command) == OnOffType.ON) {
350 if (command instanceof OnOffType) {
351 if (((OnOffType) command) == OnOffType.ON) {
358 if (command instanceof OnOffType) {
359 if (((OnOffType) command) == OnOffType.ON) {
366 if (command instanceof OnOffType) {
367 if (((OnOffType) command) == OnOffType.ON) {
376 if (command instanceof OnOffType) {
377 if (((OnOffType) command) == OnOffType.ON) {
378 autoConditioning(true);
380 autoConditioning(false);
386 if (command instanceof OnOffType) {
387 if (((OnOffType) command) == OnOffType.ON) {
394 if (command instanceof OnOffType) {
395 if (((OnOffType) command) == OnOffType.ON) {
402 if (command instanceof OnOffType) {
403 if (((OnOffType) command) == OnOffType.ON) {
404 if (vehicleState.rt == 0) {
408 if (vehicleState.rt == 1) {
416 if (command instanceof OnOffType) {
417 int valetpin = ((BigDecimal) getConfig().get(VALETPIN)).intValue();
418 if (((OnOffType) command) == OnOffType.ON) {
419 setValetMode(true, valetpin);
421 setValetMode(false, valetpin);
426 case RESET_VALET_PIN: {
427 if (command instanceof OnOffType) {
428 if (((OnOffType) command) == OnOffType.ON) {
438 } catch (IllegalArgumentException e) {
440 "An error occurred while trying to set the read-only variable associated with channel '{}' to '{}'",
441 channelID, command.toString());
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);
456 public void sendCommand(String command) {
457 sendCommand(command, "{}");
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);
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);
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);
488 protected void updateStatus(ThingStatus status) {
489 super.updateStatus(status);
493 protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
494 super.updateStatus(status, statusDetail);
498 protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
499 super.updateStatus(status, statusDetail, description);
502 public void requestData(String command) {
503 requestData(command, null);
506 public void queryVehicle(String parameter) {
507 WebTarget target = account.vehicleTarget.path(parameter);
508 sendCommand(parameter, null, target);
511 public void requestAllData() {
512 requestData(DRIVE_STATE);
513 requestData(VEHICLE_STATE);
514 requestData(CHARGE_STATE);
515 requestData(CLIMATE_STATE);
516 requestData(GUI_STATE);
519 protected boolean isAwake() {
520 return vehicle != null && "online".equals(vehicle.state) && vehicle.vehicle_id != null;
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));
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();
540 protected boolean isCharging() {
541 return chargeState != null && "Charging".equals(chargeState.charging_state);
544 protected boolean hasMovedInSleepInterval() {
545 return lastLocationChangeTimestamp > (System.currentTimeMillis()
546 - (MOVE_THRESHOLD_INTERVAL_MINUTES * 60 * 1000));
549 protected boolean allowQuery() {
550 return (isAwake() && !isInactive());
553 protected void setActive() {
555 lastLocationChangeTimestamp = System.currentTimeMillis();
560 protected boolean checkResponse(Response response, boolean immediatelyFail) {
561 if (response != null && response.getStatus() == 200) {
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");
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);
574 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
575 if (eventClient != null) {
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;
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);
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);
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);
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);
617 logger.warn("Ignoring invalid command '{}' for sunroof.", state);
622 * Sets the driver and passenger temperatures.
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
628 * @param driverTemperature in Celsius
629 * @param passenegerTemperature in Celsius
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);
639 public void setCombinedTemperature(float temperature) {
640 setTemperature(temperature, temperature);
643 public void setDriverTemperature(float temperature) {
644 setTemperature(temperature, climateState != null ? climateState.passenger_temp_setting : temperature);
647 public void setPassengerTemperature(float temperature) {
648 setTemperature(climateState != null ? climateState.driver_temp_setting : temperature, temperature);
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);
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);
665 public void closeTrunk() {
669 public void setValetMode(boolean b, Integer pin) {
670 JsonObject payloadObject = new JsonObject();
671 payloadObject.addProperty("on", b);
673 payloadObject.addProperty("password", String.format("%04d", pin));
675 sendCommand(COMMAND_SET_VALET_MODE, gson.toJson(payloadObject), account.commandTarget);
676 requestData(VEHICLE_STATE);
679 public void resetValetPin() {
680 sendCommand(COMMAND_RESET_VALET_PIN, account.commandTarget);
681 requestData(VEHICLE_STATE);
684 public void setMaxRangeCharging(boolean b) {
685 sendCommand(b ? COMMAND_CHARGE_MAX : COMMAND_CHARGE_STD, account.commandTarget);
686 requestData(CHARGE_STATE);
689 public void charge(boolean b) {
690 sendCommand(b ? COMMAND_CHARGE_START : COMMAND_CHARGE_STOP, account.commandTarget);
691 requestData(CHARGE_STATE);
694 public void flashLights() {
695 sendCommand(COMMAND_FLASH_LIGHTS, account.commandTarget);
698 public void honkHorn() {
699 sendCommand(COMMAND_HONK_HORN, account.commandTarget);
702 public void openChargePort() {
703 sendCommand(COMMAND_OPEN_CHARGE_PORT, account.commandTarget);
704 requestData(CHARGE_STATE);
707 public void lockDoors(boolean b) {
708 sendCommand(b ? COMMAND_DOOR_LOCK : COMMAND_DOOR_UNLOCK, account.commandTarget);
709 requestData(VEHICLE_STATE);
712 public void autoConditioning(boolean b) {
713 sendCommand(b ? COMMAND_AUTO_COND_START : COMMAND_AUTO_COND_STOP, account.commandTarget);
714 requestData(CLIMATE_STATE);
717 public void wakeUp() {
718 sendCommand(COMMAND_WAKE_UP, account.wakeUpTarget);
721 protected Vehicle queryVehicle() {
722 String authHeader = account.getAuthHeader();
724 if (authHeader != null) {
726 // get a list of vehicles
727 Response response = account.vehiclesTarget.request(MediaType.APPLICATION_JSON_TYPE)
728 .header("Authorization", authHeader).get();
730 logger.debug("Querying the vehicle : Response : {}:{}", response.getStatus(), response.getStatusInfo());
732 if (!checkResponse(response, true)) {
733 logger.error("An error occurred while querying the vehicle");
737 JsonObject jsonObject = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
738 Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);
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,
752 } catch (ProcessingException e) {
753 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
759 protected void queryVehicleAndUpdate() {
760 vehicle = queryVehicle();
761 if (vehicle != null) {
762 parseAndUpdate("queryVehicle", null, vehicleJSON);
766 public void parseAndUpdate(String request, String payLoad, String result) {
767 final Double LOCATION_THRESHOLD = .0000001;
769 JsonObject jsonObject = null;
772 if (request != null && result != null && !"null".equals(result)) {
773 updateStatus(ThingStatus.ONLINE);
774 // first, update state objects
777 driveState = gson.fromJson(result, DriveState.class);
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");
783 lastLatitude = driveState.latitude;
784 lastLongitude = driveState.longitude;
785 lastLocationChangeTimestamp = System.currentTimeMillis();
791 guiState = gson.fromJson(result, GUIState.class);
794 case VEHICLE_STATE: {
795 vehicleState = gson.fromJson(result, VehicleState.class);
799 chargeState = gson.fromJson(result, ChargeState.class);
801 updateState(CHANNEL_CHARGE, OnOffType.ON);
803 updateState(CHANNEL_CHARGE, OnOffType.OFF);
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));
815 case "queryVehicle": {
816 if (vehicle != null && !lastState.equals(vehicle.state)) {
817 lastState = vehicle.state;
819 // in case vehicle changed to awake, refresh all data
821 logger.debug("Vehicle is now awake, updating all data");
822 lastLocationChangeTimestamp = System.currentTimeMillis();
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");
835 boolean wasInactive = isInactive;
836 isInactive = !isCharging() && !hasMovedInSleepInterval();
838 if (!wasInactive && isInactive) {
839 lastStateTimestamp = System.currentTimeMillis();
840 logger.debug("Vehicle is inactive");
848 // secondly, reformat the response string to a JSON compliant
849 // object for some specific non-JSON compatible requests
851 case MOBILE_ENABLED_STATE: {
852 jsonObject = new JsonObject();
853 jsonObject.addProperty(MOBILE_ENABLED_STATE, result);
857 jsonObject = JsonParser.parseString(result).getAsJsonObject();
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
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() });
873 Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
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));
891 boolean proceed = true;
892 if (resultTimeStamp < lastTimeStamp && request == DRIVE_STATE) {
897 for (Map.Entry<String, JsonElement> entry : entrySet) {
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()) {
907 "The variable/value pair '{}':'{}' is successfully processed",
908 entry.getKey(), entry.getValue());
911 updateState(selector.getChannelID(), UnDefType.UNDEF);
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()) {
920 "The variable/value pair '{}':'{}' is successfully used to set property '{}'",
921 entry.getKey(), entry.getValue(), selector.getChannelID());
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 : '{}'",
934 logger.warn("The result for request '{}' is discarded due to an out of sync timestamp",
942 } catch (Exception p) {
943 logger.error("An exception occurred while parsing data received from the vehicle: '{}'", p.getMessage());
947 @SuppressWarnings("unchecked")
948 protected QuantityType<Temperature> commandToQuantityType(Command command) {
949 if (command instanceof QuantityType) {
950 return ((QuantityType<Temperature>) command).toUnit(SIUnits.CELSIUS);
952 return new QuantityType<>(new BigDecimal(command.toString()), SIUnits.CELSIUS);
955 protected float quanityToRoundedFloat(QuantityType<Temperature> quantity) {
956 return roundBigDecimal(quantity.toBigDecimal()).floatValue();
959 protected BigDecimal roundBigDecimal(BigDecimal value) {
960 return value.setScale(1, RoundingMode.HALF_EVEN);
963 protected Runnable slowStateRunnable = () -> {
964 queryVehicleAndUpdate();
966 boolean allowQuery = allowQuery();
969 requestData(CHARGE_STATE);
970 requestData(CLIMATE_STATE);
971 requestData(GUI_STATE);
972 queryVehicle(MOBILE_ENABLED_STATE);
978 logger.debug("Vehicle is neither charging nor moving, skipping updates to allow it to sleep");
984 protected Runnable fastStateRunnable = () -> {
985 if (getThing().getStatus() == ThingStatus.ONLINE) {
986 boolean allowQuery = allowQuery();
989 requestData(DRIVE_STATE);
990 requestData(VEHICLE_STATE);
996 logger.debug("Vehicle is neither charging nor moving, skipping updates to allow it to sleep");
1003 protected Runnable eventRunnable = new Runnable() {
1004 Response eventResponse;
1005 BufferedReader eventBufferedReader;
1006 InputStreamReader eventInputStreamReader;
1007 boolean isEstablished = false;
1009 protected boolean establishEventStream() {
1011 if (!isEstablished) {
1012 eventBufferedReader = null;
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();
1021 logger.debug("Event Stream: Establishing the event stream: Response: {}:{}",
1022 eventResponse.getStatus(), eventResponse.getStatusInfo());
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;
1032 isEstablished = false;
1035 if (!isEstablished) {
1036 eventIntervalErrors++;
1037 if (eventIntervalErrors >= EVENT_MAXIMUM_ERRORS_IN_INTERVAL) {
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();
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;
1054 } catch (Exception e) {
1056 "Event stream: An exception occurred while establishing the event stream for the vehicle: '{}'",
1058 isEstablished = false;
1061 return isEstablished;
1068 if (getThing().getStatus() == ThingStatus.ONLINE) {
1070 if (establishEventStream()) {
1071 String line = eventBufferedReader.readLine();
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);
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)));
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);
1104 updateState(selector.getChannelID(), UnDefType.UNDEF);
1107 Map<String, String> properties = editProperties();
1108 properties.put(selector.getChannelID(),
1109 (selector.getState(vals[i])).toString());
1110 updateProperties(properties);
1114 if (logger.isDebugEnabled()) {
1115 SimpleDateFormat dateFormatter = new SimpleDateFormat(
1116 "yyyy-MM-dd'T'HH:mm:ss.SSS");
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)));
1124 if (logger.isDebugEnabled()) {
1125 SimpleDateFormat dateFormatter = new SimpleDateFormat(
1126 "yyyy-MM-dd'T'HH:mm:ss.SSS");
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));
1133 if (systemTimeStamp - currentTimeStamp > EVENT_TIMESTAMP_MAX_DELTA) {
1134 logger.trace("Event stream: The event stream will be reset");
1135 isEstablished = false;
1138 line = eventBufferedReader.readLine();
1140 logger.trace("Event stream: The end of stream was reached");
1141 isEstablished = false;
1144 logger.debug("Event stream: The vehicle is not awake");
1145 if (vehicle != null) {
1147 // wake up the vehicle until streaming token <> 0
1148 logger.debug("Event stream: Waking up the vehicle");
1152 vehicle = queryVehicle();
1154 Thread.sleep(EVENT_STREAM_PAUSE);
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;
1164 if (Thread.interrupted()) {
1165 logger.debug("Event stream: the event stream was interrupted");