0
# Data Processing and Utilities
1
2
Utility functions for data processing, unit conversion, VIN decoding, option code lookup, and error handling with custom exception classes for Tesla API interactions.
3
4
## Capabilities
5
6
### Data Representation
7
8
Enhanced dictionary class with pretty-printing capabilities for JSON data representation.
9
10
```python { .api }
11
class JsonDict(dict):
12
"""Pretty printing dictionary with JSON string representation."""
13
14
def __str__(self):
15
"""
16
Serialize dict to JSON formatted string with indents.
17
18
Returns:
19
str: JSON formatted string with 4-space indentation
20
"""
21
```
22
23
### Exception Classes
24
25
Custom exception classes for handling Tesla API-specific errors and vehicle/product operation failures.
26
27
```python { .api }
28
class VehicleError(Exception):
29
"""
30
Vehicle-specific exception class.
31
32
Raised when vehicle commands fail or vehicle operations cannot be completed.
33
Common scenarios include commands returning False result, vehicle not responding,
34
or user not present for media commands.
35
"""
36
37
class ProductError(Exception):
38
"""
39
Product-specific exception class.
40
41
Raised when energy product (Powerwall/solar) commands fail or operations
42
cannot be completed, typically when response code is not 201.
43
"""
44
```
45
46
### Vehicle Information Decoding
47
48
Comprehensive VIN decoding functionality that extracts detailed vehicle specifications from the Vehicle Identification Number.
49
50
```python { .api }
51
def decode_vin(self):
52
"""
53
Decode vehicle identification number to detailed specification dictionary.
54
55
Returns:
56
JsonDict: Decoded VIN information containing:
57
- manufacturer (str): 'Tesla Motors, Inc.'
58
- make (str): Tesla model (e.g., 'Tesla Model 3')
59
- body_type (str): Body style and handedness
60
- belt_system (str): Seatbelt and airbag configuration
61
- battery_type (str): Battery chemistry (NMC, LFP, etc.)
62
- drive_unit (str): Motor configuration (Single/Dual/Tri Motor)
63
- year (str): Model year
64
- plant_code (str): Manufacturing plant location
65
"""
66
```
67
68
### Option Code Processing
69
70
Methods for decoding Tesla vehicle option codes into human-readable descriptions.
71
72
```python { .api }
73
@classmethod
74
def decode_option(cls, code):
75
"""
76
Return option code description or None if unknown.
77
78
Parameters:
79
- code (str): Tesla option code to decode
80
81
Returns:
82
str or None: Human-readable description of the option code, or None if code is unknown
83
84
Note:
85
Option codes appear to be deprecated by Tesla and may not be available
86
for newer vehicles.
87
"""
88
89
def option_code_list(self):
90
"""
91
Return a list of known vehicle option code descriptions.
92
93
Returns:
94
list[str]: List of human-readable descriptions for all option codes
95
associated with this vehicle
96
97
Note:
98
Filters out None values for unknown option codes.
99
"""
100
```
101
102
### Unit Conversion Utilities
103
104
Methods for converting between different unit systems based on vehicle GUI settings.
105
106
```python { .api }
107
def dist_units(self, miles, speed=False):
108
"""
109
Format and convert distance or speed to vehicle's GUI setting units.
110
111
Parameters:
112
- miles (float or None): Distance in miles or speed in mph
113
- speed (bool): Whether this is a speed measurement (default: False)
114
115
Returns:
116
str or None: Formatted distance/speed with appropriate units based on
117
vehicle's gui_distance_units setting, or None if input is None
118
119
Examples:
120
- If GUI set to km: "160.9 km" or "80.5 km/h"
121
- If GUI set to mi: "100.0 mi" or "50.0 mph"
122
"""
123
124
def temp_units(self, celcius):
125
"""
126
Format and convert temperature to vehicle's GUI setting units.
127
128
Parameters:
129
- celcius (float or None): Temperature in Celsius
130
131
Returns:
132
str or None: Formatted temperature with appropriate units based on
133
vehicle's gui_temperature_units setting, or None if input is None
134
135
Examples:
136
- If GUI set to C: "22.0 C"
137
- If GUI set to F: "71.6 F"
138
"""
139
```
140
141
### Time Formatting
142
143
Time formatting utilities that respect vehicle GUI preferences for time display.
144
145
```python { .api }
146
def gui_time(self, timestamp_ms=0):
147
"""
148
Return timestamp or current time formatted according to vehicle's GUI setting.
149
150
Parameters:
151
- timestamp_ms (int): Timestamp in milliseconds since epoch (default: 0 for current time)
152
153
Returns:
154
str: Formatted time string based on vehicle's gui_24_hour_time setting
155
156
Examples:
157
- If 24-hour time: "14:30:15"
158
- If 12-hour time: "02:30:15 PM"
159
"""
160
161
def last_seen(self):
162
"""
163
Return human-readable time since vehicle was last seen.
164
165
Returns:
166
str: Natural language description of time elapsed since last contact
167
168
Examples:
169
- "just now"
170
- "5 minutes ago"
171
- "2 hours ago"
172
- "3 days ago"
173
174
Note:
175
Uses charge_state timestamp to determine last contact time.
176
"""
177
```
178
179
### Retry Configuration
180
181
Utility class for configuring robust connection retry strategies.
182
183
```python { .api }
184
class Retry:
185
"""
186
Retry configuration class from urllib3 for handling connection failures.
187
188
Used with Tesla constructor to configure automatic retry behavior
189
for API requests when network issues occur.
190
"""
191
```
192
193
### Imported Exception Classes
194
195
All standard HTTP and OAuth exceptions are available through the teslapy module for comprehensive error handling.
196
197
```python { .api }
198
# From requests.exceptions
199
HTTPError: HTTP error responses (4xx, 5xx status codes)
200
ConnectionError: Network connection problems
201
Timeout: Request timeout errors
202
RequestException: Base exception for all requests errors
203
204
# From oauthlib.oauth2.rfc6749.errors
205
OAuth2Error: OAuth 2.0 related errors
206
InvalidClientError: Invalid client credentials
207
InvalidGrantError: Invalid authorization grant
208
InvalidRequestError: Malformed request
209
```
210
211
## Usage Examples
212
213
### Basic Utility Usage
214
215
```python
216
import teslapy
217
218
with teslapy.Tesla('elon@tesla.com') as tesla:
219
vehicles = tesla.vehicle_list()
220
vehicle = vehicles[0]
221
222
# Get vehicle data for utilities
223
vehicle.get_vehicle_data()
224
225
# Convert distances based on GUI settings
226
range_miles = vehicle['charge_state']['battery_range']
227
print(f"Range: {vehicle.dist_units(range_miles)}")
228
229
# Convert speed
230
if vehicle['drive_state']['speed']:
231
speed_mph = vehicle['drive_state']['speed']
232
print(f"Speed: {vehicle.dist_units(speed_mph, speed=True)}")
233
234
# Convert temperature
235
outside_temp = vehicle['climate_state']['outside_temp']
236
print(f"Outside temperature: {vehicle.temp_units(outside_temp)}")
237
```
238
239
### VIN Decoding Example
240
241
```python
242
# Decode vehicle identification number
243
vin_info = vehicle.decode_vin()
244
print(f"Make: {vin_info['make']}")
245
print(f"Year: {vin_info['year']}")
246
print(f"Battery: {vin_info['battery_type']}")
247
print(f"Drive: {vin_info['drive_unit']}")
248
print(f"Plant: {vin_info['plant_code']}")
249
250
# Full VIN information
251
print("Complete VIN decode:")
252
print(vin_info) # JsonDict pretty-prints as JSON
253
```
254
255
### Option Code Processing
256
257
```python
258
# Get option code descriptions (if available)
259
option_descriptions = vehicle.option_code_list()
260
if option_descriptions:
261
print("Vehicle options:")
262
for option in option_descriptions:
263
print(f" - {option}")
264
else:
265
print("No option code descriptions available")
266
267
# Decode individual option code
268
code_description = teslapy.Vehicle.decode_option('MDLS')
269
if code_description:
270
print(f"MDLS means: {code_description}")
271
```
272
273
### Time Formatting
274
275
```python
276
# Format current time according to vehicle settings
277
current_time = vehicle.gui_time()
278
print(f"Current time: {current_time}")
279
280
# Format specific timestamp
281
timestamp_ms = vehicle['charge_state']['timestamp']
282
formatted_time = vehicle.gui_time(timestamp_ms)
283
print(f"Last charge update: {formatted_time}")
284
285
# Natural language last seen
286
print(f"Vehicle last seen: {vehicle.last_seen()}")
287
```
288
289
### Error Handling with Custom Exceptions
290
291
```python
292
import teslapy
293
294
try:
295
with teslapy.Tesla('elon@tesla.com') as tesla:
296
vehicles = tesla.vehicle_list()
297
vehicle = vehicles[0]
298
299
# This might raise VehicleError if command fails
300
vehicle.command('HONK_HORN')
301
302
except teslapy.VehicleError as e:
303
print(f"Vehicle command failed: {e}")
304
# Handle vehicle-specific errors (command failed, user not present, etc.)
305
306
except teslapy.HTTPError as e:
307
print(f"HTTP error: {e}")
308
# Handle API errors (408 vehicle unavailable, 401 unauthorized, etc.)
309
if "408" in str(e):
310
print("Vehicle is asleep or offline")
311
elif "401" in str(e):
312
print("Authentication required")
313
314
except teslapy.ConnectionError as e:
315
print(f"Network connection error: {e}")
316
# Handle network connectivity issues
317
318
except teslapy.Timeout as e:
319
print(f"Request timed out: {e}")
320
# Handle timeout scenarios
321
```
322
323
### JsonDict Pretty Printing
324
325
```python
326
# JsonDict automatically formats as pretty JSON
327
vehicle_data = vehicle.get_vehicle_data()
328
print("Vehicle data:")
329
print(vehicle_data) # Outputs formatted JSON with indentation
330
331
# Manual JsonDict creation
332
custom_data = teslapy.JsonDict({
333
'battery_level': 85,
334
'range': 250,
335
'location': {'lat': 37.7749, 'lng': -122.4194}
336
})
337
print(custom_data) # Pretty-printed JSON output
338
```
339
340
### Robust Connection Configuration
341
342
```python
343
import teslapy
344
345
# Configure retry strategy for unreliable connections
346
retry = teslapy.Retry(
347
total=3, # Total number of retries
348
status_forcelist=(500, 502, 503, 504), # HTTP status codes to retry
349
backoff_factor=0.3 # Backoff between retries
350
)
351
352
with teslapy.Tesla('elon@tesla.com', retry=retry, timeout=30) as tesla:
353
try:
354
vehicles = tesla.vehicle_list()
355
# Operations will automatically retry on specified failures
356
357
except teslapy.HTTPError as e:
358
print(f"Failed after retries: {e}")
359
```
360
361
### Data Processing Pipeline
362
363
```python
364
def process_vehicle_data(vehicle):
365
"""Example data processing function using utilities."""
366
367
# Ensure we have fresh data
368
vehicle.get_vehicle_data()
369
370
# Extract and convert key metrics
371
battery_level = vehicle['charge_state']['battery_level']
372
range_remaining = vehicle.dist_units(vehicle['charge_state']['battery_range'])
373
outside_temp = vehicle.temp_units(vehicle['climate_state']['outside_temp'])
374
last_update = vehicle.gui_time(vehicle['charge_state']['timestamp'])
375
376
# Get vehicle info
377
vin_info = vehicle.decode_vin()
378
379
# Create summary
380
summary = teslapy.JsonDict({
381
'vehicle_name': vehicle['display_name'],
382
'model': vin_info['make'],
383
'year': vin_info['year'],
384
'battery_level': f"{battery_level}%",
385
'range': range_remaining,
386
'temperature': outside_temp,
387
'last_seen': vehicle.last_seen(),
388
'last_update': last_update,
389
'location': {
390
'latitude': vehicle['drive_state']['latitude'],
391
'longitude': vehicle['drive_state']['longitude']
392
}
393
})
394
395
return summary
396
397
# Process all vehicles
398
with teslapy.Tesla('elon@tesla.com') as tesla:
399
vehicles = tesla.vehicle_list()
400
for vehicle in vehicles:
401
try:
402
summary = process_vehicle_data(vehicle)
403
print(f"\n{summary['vehicle_name']} Summary:")
404
print(summary)
405
except teslapy.VehicleError as e:
406
print(f"Could not process {vehicle['display_name']}: {e}")
407
```
408
409
### Battery and Solar Utilities
410
411
```python
412
# Energy product utilities work similarly
413
with teslapy.Tesla('elon@tesla.com') as tesla:
414
batteries = tesla.battery_list()
415
solar_panels = tesla.solar_list()
416
417
for battery in batteries:
418
try:
419
battery.get_site_data()
420
421
# Create summary using JsonDict
422
battery_summary = teslapy.JsonDict({
423
'site_name': battery['site_name'],
424
'battery_level': f"{battery['percentage_charged']}%",
425
'power': f"{battery['battery_power']} W",
426
'grid_status': battery['grid_status'],
427
'operation': battery['operation']
428
})
429
print("Battery Status:")
430
print(battery_summary)
431
432
except teslapy.ProductError as e:
433
print(f"Battery error: {e}")
434
435
for solar in solar_panels:
436
try:
437
solar.get_site_data()
438
439
# Solar summary
440
solar_summary = teslapy.JsonDict({
441
'solar_power': f"{solar['solar_power']} W",
442
'grid_power': f"{solar['grid_power']} W",
443
'grid_status': solar['grid_status']
444
})
445
print("Solar Status:")
446
print(solar_summary)
447
448
except teslapy.ProductError as e:
449
print(f"Solar error: {e}")
450
```