CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-teslapy

A Python module to use the Tesla Motors Owner API for monitoring and controlling Tesla vehicles, Powerwall batteries, and solar panels remotely

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

vehicle-control.mddocs/

Vehicle Control and Monitoring

Comprehensive vehicle control functionality including wake-up, status monitoring, climate control, charging management, location tracking, and command execution for Tesla vehicles.

Capabilities

Vehicle Data Retrieval

Methods for retrieving various types of vehicle data including comprehensive vehicle state, location information, and service data.

def get_vehicle_data(self, endpoints='location_data;charge_state;climate_state;vehicle_state;gui_settings;vehicle_config'):
    """
    Get vehicle data for selected endpoints.

    Parameters:
    - endpoints (str): String containing each endpoint to query, separated by semicolons
                      (default: all endpoints)

    Returns:
    Vehicle: Updated Vehicle object

    Raises:
    HTTPError: When vehicle is not online
    """

def get_vehicle_summary(self):
    """
    Determine the state of the vehicle's various sub-systems.

    Returns:
    Vehicle: Updated Vehicle object
    """

def get_vehicle_location_data(self, max_age=300):
    """
    Get basic and location data. Wakes vehicle if location data is not present or older than max_age.

    Parameters:
    - max_age (int): How long in seconds before refreshing location data (default: 300)

    Returns:
    Vehicle: Updated Vehicle object

    Raises:
    HTTPError: When vehicle is not online
    """

def get_nearby_charging_sites(self):
    """
    List nearby Tesla-operated charging stations.

    Returns:
    dict: Response containing nearby charging sites

    Raises:
    HTTPError: When vehicle is in service or not online
    """

def get_service_scheduling_data(self):
    """
    Retrieve next service appointment for this vehicle.

    Returns:
    dict: Service scheduling data including next appointment timestamp
    """

def get_charge_history(self):
    """
    List vehicle charging history data points.

    Returns:
    dict: Response containing charging history data

    Note:
    Requires car software version 2021.44.25 or higher, Data Sharing enabled,
    and user must be primary vehicle owner.
    """

def get_charge_history_v2(self):
    """
    List vehicle charging history data points using v2 API.

    Returns:
    dict: Response containing charging history data from v2 API
    """

Vehicle State Management

Methods for managing vehicle availability, wake-up functionality, and basic state checks.

def available(self, max_age=60):
    """
    Determine vehicle availability based on cached data or refreshed status when aged out.

    Parameters:
    - max_age (int): Maximum age in seconds for cached data (default: 60)

    Returns:
    bool: True if vehicle is online, False otherwise
    """

def sync_wake_up(self, timeout=60, interval=2, backoff=1.15):
    """
    Wake up vehicle if needed and wait for it to come online.

    Parameters:
    - timeout (int): Maximum time to wait in seconds (default: 60)
    - interval (int): Initial wait interval in seconds (default: 2)
    - backoff (float): Backoff multiplier for wait interval (default: 1.15)

    Raises:
    VehicleError: When vehicle does not come online within timeout
    """

def mobile_enabled(self):
    """
    Check if the Mobile Access setting is enabled in the car.

    Returns:
    dict: Response indicating mobile access status

    Raises:
    HTTPError: When vehicle is in service or not online
    """

Vehicle Commands

Core command execution functionality with comprehensive error handling and support for all Tesla vehicle commands.

def command(self, name, **kwargs):
    """
    Wrapper method for vehicle command response error handling.

    Parameters:
    - name (str): Command name (e.g., 'UNLOCK', 'CLIMATE_ON', 'ACTUATE_TRUNK')
    - **kwargs: Command-specific parameters

    Returns:
    bool: True if command succeeded

    Raises:
    VehicleError: If command fails or doesn't return expected response
    HTTPError: On API errors
    """

def api(self, name, **kwargs):
    """
    Endpoint request with vehicle_id path variable.

    Parameters:
    - name (str): Endpoint name
    - **kwargs: Endpoint parameters

    Returns:
    dict: API response
    """

Streaming Data

Real-time vehicle data streaming using WebSocket connection for live telemetry updates.

def stream(self, callback=None, retry=0, indefinitely=False, **kwargs):
    """
    Let vehicle push on-change data, with 10 second idle timeout.

    Parameters:
    - callback (callable): Function with one argument (dict of pushed data) (optional)
    - retry (int): Number of connection retries (default: 0)
    - indefinitely (bool): Retry indefinitely (default: False)
    - **kwargs: Optional arguments for WebSocket run_forever method

    Note:
    Vehicle automatically stops streaming after 10 seconds of no changes.
    Callback function receives dict with telemetry data including speed, odometer,
    battery level, location, power, and other real-time metrics.
    """

Data Processing and Utilities

Utility methods for processing vehicle data, unit conversion, and information decoding.

def dist_units(self, miles, speed=False):
    """
    Format and convert distance or speed to GUI setting units.

    Parameters:
    - miles (float or None): Distance in miles
    - speed (bool): Whether this is a speed measurement (default: False)

    Returns:
    str or None: Formatted distance/speed with units, or None if input is None
    """

def temp_units(self, celcius):
    """
    Format and convert temperature to GUI setting units.

    Parameters:
    - celcius (float or None): Temperature in Celsius

    Returns:
    str or None: Formatted temperature with units, or None if input is None
    """

def gui_time(self, timestamp_ms=0):
    """
    Return timestamp or current time formatted to GUI setting.

    Parameters:
    - timestamp_ms (int): Timestamp in milliseconds (default: 0 for current time)

    Returns:
    str: Formatted time string based on vehicle's 24-hour time setting
    """

def last_seen(self):
    """
    Return vehicle last seen natural time.

    Returns:
    str: Human-readable time since last seen (e.g., "5 minutes ago", "just now")
    """

def decode_vin(self):
    """
    Decode vehicle identification number to dict.

    Returns:
    JsonDict: Decoded VIN information including manufacturer, make, body type,
             belt system, battery type, drive unit, year, and plant code
    """

Option Codes

Methods for working with Tesla vehicle option codes and their descriptions.

@classmethod
def decode_option(cls, code):
    """
    Return option code title or None if unknown.

    Parameters:
    - code (str): Option code to decode

    Returns:
    str or None: Option code description or None if unknown
    """

def option_code_list(self):
    """
    Return a list of known vehicle option code titles.

    Returns:
    list[str]: List of option code descriptions for this vehicle

    Note:
    Option codes appear to be deprecated by Tesla.
    """

Image Composition

Generate composed vehicle images based on vehicle configuration and option codes.

def compose_image(self, view='STUD_3QTR', size=640, options=None):
    """
    Return a PNG formatted composed vehicle image.

    Parameters:
    - view (str): View type - 'STUD_3QTR', 'STUD_SEAT', 'STUD_SIDE', 'STUD_REAR', 'STUD_WHEEL' (default: 'STUD_3QTR')
    - size (int): Image size in pixels (default: 640)
    - options (str): Option codes string (optional, uses vehicle's option_codes if None)

    Returns:
    bytes: PNG image data

    Raises:
    ValueError: If options is None and vehicle has no option_codes
    HTTPError: On image retrieval errors
    """

Major Vehicle Commands

Door and Access Commands

# Unlock/lock vehicle
vehicle.command('UNLOCK')
vehicle.command('LOCK')

# Horn and lights
vehicle.command('HONK_HORN')
vehicle.command('FLASH_LIGHTS')

# Trunk control
vehicle.command('ACTUATE_TRUNK', which_trunk='rear')    # or 'front'

# Remote start
vehicle.command('REMOTE_START')

# Window control (requires location for close)
vehicle.command('WINDOW_CONTROL', command='vent', lat=0, lon=0)
vehicle.command('WINDOW_CONTROL', command='close', lat=latitude, lon=longitude)

# Homelink
vehicle.command('TRIGGER_HOMELINK', lat=latitude, lon=longitude)

Climate Control Commands

# Climate control
vehicle.command('CLIMATE_ON')
vehicle.command('CLIMATE_OFF')

# Temperature setting
vehicle.command('CHANGE_CLIMATE_TEMPERATURE_SETTING', 
                driver_temp=22, passenger_temp=22)

# Climate keeper mode
vehicle.command('SET_CLIMATE_KEEPER_MODE', climate_keeper_mode=1)  # 0=off, 1=on, 2=dog, 3=camp

# Defrost and bioweapon mode
vehicle.command('MAX_DEFROST', on=True)
vehicle.command('HVAC_BIOWEAPON_MODE', on=True)

# Cabin overheat protection
vehicle.command('SET_CABIN_OVERHEAT_PROTECTION', on=True, fan_only=False)

# Seat heating/cooling
vehicle.command('REMOTE_SEAT_HEATER_REQUEST', heater=0, level=3)  # seat 0-5, level 0-3
vehicle.command('REMOTE_SEAT_COOLING_REQUEST', seat_position=0, seat_cooler_level=1)
vehicle.command('REMOTE_AUTO_SEAT_CLIMATE_REQUEST', auto_seat_position=1, auto_climate_on=True)

# Steering wheel heater
vehicle.command('REMOTE_STEERING_WHEEL_HEATER_REQUEST', on=True)

Charging Commands

# Charge port control
vehicle.command('CHARGE_PORT_DOOR_OPEN')
vehicle.command('CHARGE_PORT_DOOR_CLOSE')

# Charging control
vehicle.command('START_CHARGE')
vehicle.command('STOP_CHARGE')

# Charge limit
vehicle.command('CHANGE_CHARGE_LIMIT', percent=80)

# Charging amps (requires car version 2021.36+)
vehicle.command('CHARGING_AMPS', charging_amps=16)  # 0-32A

# Scheduled charging (requires car version 2021.36+)
vehicle.command('SCHEDULED_CHARGING', enable=True, time=420)  # minutes past midnight

# Scheduled departure (requires car version 2021.36+)
vehicle.command('SCHEDULED_DEPARTURE', 
                enable=True, 
                departure_time=480,  # minutes past midnight
                preconditioning_enabled=True,
                preconditioning_weekdays_only=False,
                off_peak_charging_enabled=True,
                off_peak_charging_weekdays_only=True,
                end_off_peak_time=360)

Media and Entertainment Commands

# Media control
vehicle.command('MEDIA_TOGGLE_PLAYBACK')
vehicle.command('MEDIA_NEXT_TRACK')
vehicle.command('MEDIA_PREVIOUS_TRACK')
vehicle.command('MEDIA_NEXT_FAVORITE')
vehicle.command('MEDIA_PREVIOUS_FAVORITE')
vehicle.command('MEDIA_VOLUME_UP')
vehicle.command('MEDIA_VOLUME_DOWN')

Security and Speed Limit Commands

# Valet mode
vehicle.command('SET_VALET_MODE', on=True, password='1234')
vehicle.command('RESET_VALET_PIN')

# Speed limit
vehicle.command('SPEED_LIMIT_ACTIVATE', pin='1234')
vehicle.command('SPEED_LIMIT_DEACTIVATE', pin='1234')
vehicle.command('SPEED_LIMIT_SET_LIMIT', limit_mph=65)  # 50-90 mph
vehicle.command('SPEED_LIMIT_CLEAR_PIN', pin='1234')

# Sentry mode
vehicle.command('SET_SENTRY_MODE', on=True)

Software Update Commands

# Software updates
vehicle.command('SCHEDULE_SOFTWARE_UPDATE', offset_sec=3600)  # seconds
vehicle.command('CANCEL_SOFTWARE_UPDATE')

Vehicle Configuration Commands

# Vehicle name
vehicle.command('SET_VEHICLE_NAME', vehicle_name="My Tesla")

# Sunroof control
vehicle.command('CHANGE_SUNROOF_STATE', state='vent')  # or 'close'

# Cabin overheat protection temperature
vehicle.command('SET_COP_TEMP', temp=35)  # temperature in Celsius

Usage Examples

Basic Vehicle Control

import teslapy

with teslapy.Tesla('elon@tesla.com') as tesla:
    vehicles = tesla.vehicle_list()
    vehicle = vehicles[0]
    
    # Check if vehicle is available
    if vehicle.available():
        print("Vehicle is online")
    else:
        print("Waking up vehicle...")
        vehicle.sync_wake_up()
    
    # Get comprehensive vehicle data
    vehicle.get_vehicle_data()
    print(f"Battery level: {vehicle['charge_state']['battery_level']}%")
    print(f"Range: {vehicle.dist_units(vehicle['charge_state']['battery_range'])}")

Climate Control Example

# Turn on climate and set temperature
vehicle.command('CLIMATE_ON')
vehicle.command('CHANGE_CLIMATE_TEMPERATURE_SETTING', driver_temp=22, passenger_temp=20)

# Turn on seat heaters for driver and passenger
vehicle.command('REMOTE_SEAT_HEATER_REQUEST', heater=0, level=2)  # driver seat
vehicle.command('REMOTE_SEAT_HEATER_REQUEST', heater=1, level=2)  # passenger seat

# Enable bioweapon defense mode
vehicle.command('HVAC_BIOWEAPON_MODE', on=True)

Charging Management Example

# Open charge port and start charging
vehicle.command('CHARGE_PORT_DOOR_OPEN')
vehicle.command('START_CHARGE')

# Set charge limit to 80%
vehicle.command('CHANGE_CHARGE_LIMIT', percent=80)

# Schedule charging to start at 2 AM
vehicle.command('SCHEDULED_CHARGING', enable=True, time=120)  # 2 AM = 120 minutes past midnight

Streaming Data Example

def handle_streaming_data(data):
    print(f"Speed: {data['speed']} mph")
    print(f"Battery: {data['soc']}%")
    print(f"Power: {data['power']} kW")

# Stream real-time data
vehicle.stream(callback=handle_streaming_data, retry=3)

Error Handling

try:
    vehicle.command('HONK_HORN')
except teslapy.VehicleError as e:
    print(f"Vehicle command failed: {e}")
except teslapy.HTTPError as e:
    if "408" in str(e):
        print("Vehicle is unavailable - it may be asleep")
    else:
        print(f"API error: {e}")

Location and Service Data

# Get location data (wakes vehicle if needed)
vehicle.get_vehicle_location_data()
latitude = vehicle['drive_state']['latitude']
longitude = vehicle['drive_state']['longitude']

# Find nearby charging sites
charging_sites = vehicle.get_nearby_charging_sites()
for site in charging_sites['superchargers']:
    print(f"{site['name']}: {site['distance_miles']} miles away")

# Check service scheduling
service_data = vehicle.get_service_scheduling_data()
if service_data.get('next_appt_timestamp'):
    print(f"Next service: {service_data['next_appt_timestamp']}")

Install with Tessl CLI

npx tessl i tessl/pypi-teslapy

docs

authentication.md

energy-products.md

index.md

utilities.md

vehicle-control.md

tile.json