TeslaPy
A Python module to use the Tesla Motors Owner API
Install / Use
/learn @tdorssers/TeslaPyREADME
TeslaPy
A Python implementation based on unofficial documentation of the client side interface to the Tesla Motors Owner API, which provides functionality to monitor and control Tesla products remotely.
The Owner API will stop working as vehicles begin requiring end-to-end command authentication using the Tesla Vehicle Command Protocol. Pre-2021 Model S and X vehicles do not support this new protocol and remain controllable using TeslaPy.
Overview
This module depends on Python requests, requests_oauthlib and websocket-client. It requires Python 3.10+ when using urllib3 2.0, which comes with requests 2.30.0+, or you can pin urllib3 to 1.26.x by installing urllib3<2.
The Tesla class extends requests_oauthlib.OAuth2Session which extends requests.Session and therefore inherits methods like get() and post() that can be used to perform API calls. Module characteristics:
- It implements Tesla's new OAuth 2 Single Sign-On service.
- Acquired tokens are stored in current working directory in cache.json file for persistence by default.
- The cache stores tokens of each authorized identity (email).
- Authentication is only needed when a new token is requested (usually once).
- The token is automatically refreshed when expired without the need to reauthenticate.
- An email registered in another region (e.g. auth.tesla.cn) is also supported.
- Streaming API support using a WebSocket.
- Pluggable cache and authenticator methods.
TeslaPy 2.0.0+ no longer implements headless authentication. The constructor differs and takes these arguments:
| Argument | Description |
| --- | --- |
| email | SSO identity |
| verify | (optional) verify SSL certificate |
| proxy | (optional) URL of proxy server |
| retry | (optional) number of connection retries or Retry instance |
| timeout | (optional) Connect/read timeout |
| user_agent | (optional) the User-Agent string |
| authenticator | (optional) Function with one argument, the authorization URL, that returns the redirected URL |
| cache_file | (optional) path to cache file used by default loader and dumper |
| cache_loader | (optional) function that returns the cache dict |
| cache_dumper | (optional) function with one argument, the cache dict |
| sso_base_url | (optional) URL of SSO service, set to https://auth.tesla.cn/ if your email is registered in another region |
| state | (optional) state string for CSRF protection |
| code_verifier | (optional) PKCE code verifier string |
| app_user_agent | (optional) X-Tesla-User-Agent string |
TeslaPy 2.1.0+ no longer implements RFC 7523 and uses the SSO token for all API requests.
The class will open Tesla's SSO page in the system's default web browser to authenticate. After successful authentication, a Page not found will be displayed and the URL should start with https://auth.tesla.com/void/callback, which is the redirected URL. The class will use stdio to get the full redirected URL from the web browser by default. You need to copy and paste the full URL from the web browser to the console to continue aquirering API tokens. You can use a pluggable authenticator method to automate this, for example using pywebview or selenium. It is also possible to use an SSO refresh token obtained by a 3rd party authentication app.
The convenience method api() uses named endpoints listed in endpoints.json to perform calls, so the module does not require changes if the API is updated. api() substitutes path variables in the URI and calls fetch_token() when needed. Any error message returned by the API is raised as an HTTPError exception. Additionally, the class implements the following methods:
| Call | Description |
| --- | --- |
| request() | performs API call using relative or absolute URL, serialization and error message handling |
| new_code_verifier() | generates code verifier for PKCE |
| authorization_url() | forms authorization URL with PKCE extension and tries to detect the accounts registered region |
| fetch_token() | requests an SSO token using Authorization Code grant with PKCE extension |
| refresh_token() | requests an SSO token using Refresh Token grant |
| close() | remove all requests adapter instances |
| logout() | removes token from cache, returns logout URL and optionally signs out using system's default web browser |
| vehicle_list() | returns a list of Vehicle objects |
| battery_list() | returns a list of Battery objects |
| solar_list() | returns a list of SolarPanel objects |
The Vehicle class extends dict and stores vehicle data returned by the Owner API, which is a pull API. The get_vehicle_summary() and get_vehicle_data() calls update the Vehicle instance, merging data. The streaming API pushes vehicle data on-change after subscription. The stream() method takes an optional argument, a callback function that is called with one argument, a dict holding the changed data. The Vehicle object is always updated with the pushed data. If there are no changes within 10 seconds, the vehicle stops streaming data. The stream() method has two more optional arguments to control restarting. Additionally, the class implements the following methods:
| Call | Online | Description |
| --- | --- | --- |
| api() | Yes | performs an API call to named endpoint requiring vehicle_id with optional arguments |
| get_vehicle_summary() | No | gets the state of the vehicle (online, asleep, offline) |
| available() | No | checks if the vehicle is online based on cached data or refreshed status when aged out |
| sync_wake_up() | No | wakes up and waits for the vehicle to come online |
| decode_option() | No | lookup option code description (read from option_codes.json) |
| option_code_list() <sup>1</sup> | No | lists known descriptions of the vehicle option codes |
| get_vehicle_data() | Yes | get vehicle data for selected endpoints, defaults to all endpoints|
| get_vehicle_location_data() | Yes | gets the basic and location data for the vehicle|
| get_nearby_charging_sites() | Yes | lists nearby Tesla-operated charging stations |
| get_service_scheduling_data() | No | retrieves next service appointment for this vehicle |
| get_charge_history() <sup>2</sup> | No | lists vehicle charging history data points |
| mobile_enabled() | Yes | checks if the Mobile Access setting is enabled in the car |
| compose_image() <sup>3</sup> | No | composes a vehicle image based on vehicle option codes |
| dist_units() | No | converts distance or speed units to GUI setting of the vehicle |
| temp_units() | No | converts temperature units to GUI setting of the vehicle |
| gui_time() | No | returns timestamp or current time formatted to GUI setting |
| last_seen() | No | returns vehicle last seen natural time |
| decode_vin() | No | decodes the vehicle identification number to a dict |
| command() | Yes | wrapper around api() for vehicle command response error handling |
<sup>1</sup> Option codes appear to be deprecated.
<sup>2</sup> Car software version 2021.44.25 or higher required, Data Sharing must be enabled and you must be the primary vehicle owner.
<sup>3</sup> Pass vehicle option codes to this method now options codes are deprecated.
Only methods with No in the Online column are available when the vehicle is asleep or offline. These methods will not prevent your vehicle from sleeping. Other methods and API calls require the vehicle to be brought online by using sync_wake_up() and can prevent your vehicle from sleeping if called within too short a period.
The Product class extends dict and is initialized with product data of Powerwalls and solar panels returned by the API. Additionally, the class implements the following methods:
| Call | Description |
| --- | --- |
| api() | performs an API call to named endpoint requiring battery_id or site_id with optional arguments |
| get_history_data() | Retrieve live status of product |
| get_calendar_history_data() | Retrieve live status of product |
| command() | wrapper around api() for battery command response error handling |
The Battery class extends Product and stores Powerwall data returned by the API, updated by get_battery_data(). Additionally, the class implements the following methods:
| Call | Description |
| --- | --- |
| get_battery_data() | Retrieve detailed state and configuration of the battery |
| set_operation() | Set battery operation to self_consumption, backup or autonomous |
| set_backup_reserve_percent() | Set the minimum backup reserve percent for that battery |
| set_import_export() | Sets the battery grid import and export settings |
| get_tariff() | Get the tariff rate data |
| set_tariff() | Set the tariff rate data. The data can be created manually, or generated by create_tariff |
| create_tariff() | Creates a correctly formatted dictionary of tariff data |
The SolarPanel class extends Product and stores solar panel data returned by the API, updated by get_site_data(). Additionally, the class impl
