0
# Vehicle Control and Monitoring
1
2
Comprehensive vehicle control functionality including wake-up, status monitoring, climate control, charging management, location tracking, and command execution for Tesla vehicles.
3
4
## Capabilities
5
6
### Vehicle Data Retrieval
7
8
Methods for retrieving various types of vehicle data including comprehensive vehicle state, location information, and service data.
9
10
```python { .api }
11
def get_vehicle_data(self, endpoints='location_data;charge_state;climate_state;vehicle_state;gui_settings;vehicle_config'):
12
"""
13
Get vehicle data for selected endpoints.
14
15
Parameters:
16
- endpoints (str): String containing each endpoint to query, separated by semicolons
17
(default: all endpoints)
18
19
Returns:
20
Vehicle: Updated Vehicle object
21
22
Raises:
23
HTTPError: When vehicle is not online
24
"""
25
26
def get_vehicle_summary(self):
27
"""
28
Determine the state of the vehicle's various sub-systems.
29
30
Returns:
31
Vehicle: Updated Vehicle object
32
"""
33
34
def get_vehicle_location_data(self, max_age=300):
35
"""
36
Get basic and location data. Wakes vehicle if location data is not present or older than max_age.
37
38
Parameters:
39
- max_age (int): How long in seconds before refreshing location data (default: 300)
40
41
Returns:
42
Vehicle: Updated Vehicle object
43
44
Raises:
45
HTTPError: When vehicle is not online
46
"""
47
48
def get_nearby_charging_sites(self):
49
"""
50
List nearby Tesla-operated charging stations.
51
52
Returns:
53
dict: Response containing nearby charging sites
54
55
Raises:
56
HTTPError: When vehicle is in service or not online
57
"""
58
59
def get_service_scheduling_data(self):
60
"""
61
Retrieve next service appointment for this vehicle.
62
63
Returns:
64
dict: Service scheduling data including next appointment timestamp
65
"""
66
67
def get_charge_history(self):
68
"""
69
List vehicle charging history data points.
70
71
Returns:
72
dict: Response containing charging history data
73
74
Note:
75
Requires car software version 2021.44.25 or higher, Data Sharing enabled,
76
and user must be primary vehicle owner.
77
"""
78
79
def get_charge_history_v2(self):
80
"""
81
List vehicle charging history data points using v2 API.
82
83
Returns:
84
dict: Response containing charging history data from v2 API
85
"""
86
```
87
88
### Vehicle State Management
89
90
Methods for managing vehicle availability, wake-up functionality, and basic state checks.
91
92
```python { .api }
93
def available(self, max_age=60):
94
"""
95
Determine vehicle availability based on cached data or refreshed status when aged out.
96
97
Parameters:
98
- max_age (int): Maximum age in seconds for cached data (default: 60)
99
100
Returns:
101
bool: True if vehicle is online, False otherwise
102
"""
103
104
def sync_wake_up(self, timeout=60, interval=2, backoff=1.15):
105
"""
106
Wake up vehicle if needed and wait for it to come online.
107
108
Parameters:
109
- timeout (int): Maximum time to wait in seconds (default: 60)
110
- interval (int): Initial wait interval in seconds (default: 2)
111
- backoff (float): Backoff multiplier for wait interval (default: 1.15)
112
113
Raises:
114
VehicleError: When vehicle does not come online within timeout
115
"""
116
117
def mobile_enabled(self):
118
"""
119
Check if the Mobile Access setting is enabled in the car.
120
121
Returns:
122
dict: Response indicating mobile access status
123
124
Raises:
125
HTTPError: When vehicle is in service or not online
126
"""
127
```
128
129
### Vehicle Commands
130
131
Core command execution functionality with comprehensive error handling and support for all Tesla vehicle commands.
132
133
```python { .api }
134
def command(self, name, **kwargs):
135
"""
136
Wrapper method for vehicle command response error handling.
137
138
Parameters:
139
- name (str): Command name (e.g., 'UNLOCK', 'CLIMATE_ON', 'ACTUATE_TRUNK')
140
- **kwargs: Command-specific parameters
141
142
Returns:
143
bool: True if command succeeded
144
145
Raises:
146
VehicleError: If command fails or doesn't return expected response
147
HTTPError: On API errors
148
"""
149
150
def api(self, name, **kwargs):
151
"""
152
Endpoint request with vehicle_id path variable.
153
154
Parameters:
155
- name (str): Endpoint name
156
- **kwargs: Endpoint parameters
157
158
Returns:
159
dict: API response
160
"""
161
```
162
163
### Streaming Data
164
165
Real-time vehicle data streaming using WebSocket connection for live telemetry updates.
166
167
```python { .api }
168
def stream(self, callback=None, retry=0, indefinitely=False, **kwargs):
169
"""
170
Let vehicle push on-change data, with 10 second idle timeout.
171
172
Parameters:
173
- callback (callable): Function with one argument (dict of pushed data) (optional)
174
- retry (int): Number of connection retries (default: 0)
175
- indefinitely (bool): Retry indefinitely (default: False)
176
- **kwargs: Optional arguments for WebSocket run_forever method
177
178
Note:
179
Vehicle automatically stops streaming after 10 seconds of no changes.
180
Callback function receives dict with telemetry data including speed, odometer,
181
battery level, location, power, and other real-time metrics.
182
"""
183
```
184
185
### Data Processing and Utilities
186
187
Utility methods for processing vehicle data, unit conversion, and information decoding.
188
189
```python { .api }
190
def dist_units(self, miles, speed=False):
191
"""
192
Format and convert distance or speed to GUI setting units.
193
194
Parameters:
195
- miles (float or None): Distance in miles
196
- speed (bool): Whether this is a speed measurement (default: False)
197
198
Returns:
199
str or None: Formatted distance/speed with units, or None if input is None
200
"""
201
202
def temp_units(self, celcius):
203
"""
204
Format and convert temperature to GUI setting units.
205
206
Parameters:
207
- celcius (float or None): Temperature in Celsius
208
209
Returns:
210
str or None: Formatted temperature with units, or None if input is None
211
"""
212
213
def gui_time(self, timestamp_ms=0):
214
"""
215
Return timestamp or current time formatted to GUI setting.
216
217
Parameters:
218
- timestamp_ms (int): Timestamp in milliseconds (default: 0 for current time)
219
220
Returns:
221
str: Formatted time string based on vehicle's 24-hour time setting
222
"""
223
224
def last_seen(self):
225
"""
226
Return vehicle last seen natural time.
227
228
Returns:
229
str: Human-readable time since last seen (e.g., "5 minutes ago", "just now")
230
"""
231
232
def decode_vin(self):
233
"""
234
Decode vehicle identification number to dict.
235
236
Returns:
237
JsonDict: Decoded VIN information including manufacturer, make, body type,
238
belt system, battery type, drive unit, year, and plant code
239
"""
240
```
241
242
### Option Codes
243
244
Methods for working with Tesla vehicle option codes and their descriptions.
245
246
```python { .api }
247
@classmethod
248
def decode_option(cls, code):
249
"""
250
Return option code title or None if unknown.
251
252
Parameters:
253
- code (str): Option code to decode
254
255
Returns:
256
str or None: Option code description or None if unknown
257
"""
258
259
def option_code_list(self):
260
"""
261
Return a list of known vehicle option code titles.
262
263
Returns:
264
list[str]: List of option code descriptions for this vehicle
265
266
Note:
267
Option codes appear to be deprecated by Tesla.
268
"""
269
```
270
271
### Image Composition
272
273
Generate composed vehicle images based on vehicle configuration and option codes.
274
275
```python { .api }
276
def compose_image(self, view='STUD_3QTR', size=640, options=None):
277
"""
278
Return a PNG formatted composed vehicle image.
279
280
Parameters:
281
- view (str): View type - 'STUD_3QTR', 'STUD_SEAT', 'STUD_SIDE', 'STUD_REAR', 'STUD_WHEEL' (default: 'STUD_3QTR')
282
- size (int): Image size in pixels (default: 640)
283
- options (str): Option codes string (optional, uses vehicle's option_codes if None)
284
285
Returns:
286
bytes: PNG image data
287
288
Raises:
289
ValueError: If options is None and vehicle has no option_codes
290
HTTPError: On image retrieval errors
291
"""
292
```
293
294
## Major Vehicle Commands
295
296
### Door and Access Commands
297
298
```python
299
# Unlock/lock vehicle
300
vehicle.command('UNLOCK')
301
vehicle.command('LOCK')
302
303
# Horn and lights
304
vehicle.command('HONK_HORN')
305
vehicle.command('FLASH_LIGHTS')
306
307
# Trunk control
308
vehicle.command('ACTUATE_TRUNK', which_trunk='rear') # or 'front'
309
310
# Remote start
311
vehicle.command('REMOTE_START')
312
313
# Window control (requires location for close)
314
vehicle.command('WINDOW_CONTROL', command='vent', lat=0, lon=0)
315
vehicle.command('WINDOW_CONTROL', command='close', lat=latitude, lon=longitude)
316
317
# Homelink
318
vehicle.command('TRIGGER_HOMELINK', lat=latitude, lon=longitude)
319
```
320
321
### Climate Control Commands
322
323
```python
324
# Climate control
325
vehicle.command('CLIMATE_ON')
326
vehicle.command('CLIMATE_OFF')
327
328
# Temperature setting
329
vehicle.command('CHANGE_CLIMATE_TEMPERATURE_SETTING',
330
driver_temp=22, passenger_temp=22)
331
332
# Climate keeper mode
333
vehicle.command('SET_CLIMATE_KEEPER_MODE', climate_keeper_mode=1) # 0=off, 1=on, 2=dog, 3=camp
334
335
# Defrost and bioweapon mode
336
vehicle.command('MAX_DEFROST', on=True)
337
vehicle.command('HVAC_BIOWEAPON_MODE', on=True)
338
339
# Cabin overheat protection
340
vehicle.command('SET_CABIN_OVERHEAT_PROTECTION', on=True, fan_only=False)
341
342
# Seat heating/cooling
343
vehicle.command('REMOTE_SEAT_HEATER_REQUEST', heater=0, level=3) # seat 0-5, level 0-3
344
vehicle.command('REMOTE_SEAT_COOLING_REQUEST', seat_position=0, seat_cooler_level=1)
345
vehicle.command('REMOTE_AUTO_SEAT_CLIMATE_REQUEST', auto_seat_position=1, auto_climate_on=True)
346
347
# Steering wheel heater
348
vehicle.command('REMOTE_STEERING_WHEEL_HEATER_REQUEST', on=True)
349
```
350
351
### Charging Commands
352
353
```python
354
# Charge port control
355
vehicle.command('CHARGE_PORT_DOOR_OPEN')
356
vehicle.command('CHARGE_PORT_DOOR_CLOSE')
357
358
# Charging control
359
vehicle.command('START_CHARGE')
360
vehicle.command('STOP_CHARGE')
361
362
# Charge limit
363
vehicle.command('CHANGE_CHARGE_LIMIT', percent=80)
364
365
# Charging amps (requires car version 2021.36+)
366
vehicle.command('CHARGING_AMPS', charging_amps=16) # 0-32A
367
368
# Scheduled charging (requires car version 2021.36+)
369
vehicle.command('SCHEDULED_CHARGING', enable=True, time=420) # minutes past midnight
370
371
# Scheduled departure (requires car version 2021.36+)
372
vehicle.command('SCHEDULED_DEPARTURE',
373
enable=True,
374
departure_time=480, # minutes past midnight
375
preconditioning_enabled=True,
376
preconditioning_weekdays_only=False,
377
off_peak_charging_enabled=True,
378
off_peak_charging_weekdays_only=True,
379
end_off_peak_time=360)
380
```
381
382
### Media and Entertainment Commands
383
384
```python
385
# Media control
386
vehicle.command('MEDIA_TOGGLE_PLAYBACK')
387
vehicle.command('MEDIA_NEXT_TRACK')
388
vehicle.command('MEDIA_PREVIOUS_TRACK')
389
vehicle.command('MEDIA_NEXT_FAVORITE')
390
vehicle.command('MEDIA_PREVIOUS_FAVORITE')
391
vehicle.command('MEDIA_VOLUME_UP')
392
vehicle.command('MEDIA_VOLUME_DOWN')
393
```
394
395
### Security and Speed Limit Commands
396
397
```python
398
# Valet mode
399
vehicle.command('SET_VALET_MODE', on=True, password='1234')
400
vehicle.command('RESET_VALET_PIN')
401
402
# Speed limit
403
vehicle.command('SPEED_LIMIT_ACTIVATE', pin='1234')
404
vehicle.command('SPEED_LIMIT_DEACTIVATE', pin='1234')
405
vehicle.command('SPEED_LIMIT_SET_LIMIT', limit_mph=65) # 50-90 mph
406
vehicle.command('SPEED_LIMIT_CLEAR_PIN', pin='1234')
407
408
# Sentry mode
409
vehicle.command('SET_SENTRY_MODE', on=True)
410
```
411
412
### Software Update Commands
413
414
```python
415
# Software updates
416
vehicle.command('SCHEDULE_SOFTWARE_UPDATE', offset_sec=3600) # seconds
417
vehicle.command('CANCEL_SOFTWARE_UPDATE')
418
```
419
420
### Vehicle Configuration Commands
421
422
```python
423
# Vehicle name
424
vehicle.command('SET_VEHICLE_NAME', vehicle_name="My Tesla")
425
426
# Sunroof control
427
vehicle.command('CHANGE_SUNROOF_STATE', state='vent') # or 'close'
428
429
# Cabin overheat protection temperature
430
vehicle.command('SET_COP_TEMP', temp=35) # temperature in Celsius
431
```
432
433
## Usage Examples
434
435
### Basic Vehicle Control
436
437
```python
438
import teslapy
439
440
with teslapy.Tesla('elon@tesla.com') as tesla:
441
vehicles = tesla.vehicle_list()
442
vehicle = vehicles[0]
443
444
# Check if vehicle is available
445
if vehicle.available():
446
print("Vehicle is online")
447
else:
448
print("Waking up vehicle...")
449
vehicle.sync_wake_up()
450
451
# Get comprehensive vehicle data
452
vehicle.get_vehicle_data()
453
print(f"Battery level: {vehicle['charge_state']['battery_level']}%")
454
print(f"Range: {vehicle.dist_units(vehicle['charge_state']['battery_range'])}")
455
```
456
457
### Climate Control Example
458
459
```python
460
# Turn on climate and set temperature
461
vehicle.command('CLIMATE_ON')
462
vehicle.command('CHANGE_CLIMATE_TEMPERATURE_SETTING', driver_temp=22, passenger_temp=20)
463
464
# Turn on seat heaters for driver and passenger
465
vehicle.command('REMOTE_SEAT_HEATER_REQUEST', heater=0, level=2) # driver seat
466
vehicle.command('REMOTE_SEAT_HEATER_REQUEST', heater=1, level=2) # passenger seat
467
468
# Enable bioweapon defense mode
469
vehicle.command('HVAC_BIOWEAPON_MODE', on=True)
470
```
471
472
### Charging Management Example
473
474
```python
475
# Open charge port and start charging
476
vehicle.command('CHARGE_PORT_DOOR_OPEN')
477
vehicle.command('START_CHARGE')
478
479
# Set charge limit to 80%
480
vehicle.command('CHANGE_CHARGE_LIMIT', percent=80)
481
482
# Schedule charging to start at 2 AM
483
vehicle.command('SCHEDULED_CHARGING', enable=True, time=120) # 2 AM = 120 minutes past midnight
484
```
485
486
### Streaming Data Example
487
488
```python
489
def handle_streaming_data(data):
490
print(f"Speed: {data['speed']} mph")
491
print(f"Battery: {data['soc']}%")
492
print(f"Power: {data['power']} kW")
493
494
# Stream real-time data
495
vehicle.stream(callback=handle_streaming_data, retry=3)
496
```
497
498
### Error Handling
499
500
```python
501
try:
502
vehicle.command('HONK_HORN')
503
except teslapy.VehicleError as e:
504
print(f"Vehicle command failed: {e}")
505
except teslapy.HTTPError as e:
506
if "408" in str(e):
507
print("Vehicle is unavailable - it may be asleep")
508
else:
509
print(f"API error: {e}")
510
```
511
512
### Location and Service Data
513
514
```python
515
# Get location data (wakes vehicle if needed)
516
vehicle.get_vehicle_location_data()
517
latitude = vehicle['drive_state']['latitude']
518
longitude = vehicle['drive_state']['longitude']
519
520
# Find nearby charging sites
521
charging_sites = vehicle.get_nearby_charging_sites()
522
for site in charging_sites['superchargers']:
523
print(f"{site['name']}: {site['distance_miles']} miles away")
524
525
# Check service scheduling
526
service_data = vehicle.get_service_scheduling_data()
527
if service_data.get('next_appt_timestamp'):
528
print(f"Next service: {service_data['next_appt_timestamp']}")
529
```