mlowijs / tesla_api Goto Github PK
View Code? Open in Web Editor NEWLightweight Python API client for the Tesla API.
License: MIT License
Lightweight Python API client for the Tesla API.
License: MIT License
This just started this morning...currently happening on two separate machines.
Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:37:30) [MSC v.1927 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
=================== RESTART: C:\Python\Powerwall 3\tesla5%.py ==================
Traceback (most recent call last):
File "C:\Python\Powerwall 3\tesla5%.py", line 14, in
asyncio.run(main())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Python\Powerwall 3\tesla5%.py", line 7, in main
energy_sites = await client.list_energy_sites()
File "C:\Python\Powerwall 3\tesla_api_init_.py", line 174, in list_energy_sites
for product in await self.get("products") if "energy_site_id" in product]
File "C:\Python\Powerwall 3\tesla_api_init_.py", line 142, in get
await self.authenticate()
File "C:\Python\Powerwall 3\tesla_api_init_.py", line 130, in authenticate
self._token = await self.get_new_token()
File "C:\Python\Powerwall 3\tesla_api_init.py", line 90, in _get_new_token
redirect_location = resp.headers["Location"]
KeyError: 'Location'
Hi, just trying to run you for example to get the vehicles/vin and this error occurs:
Traceback (most recent call last):
File "myv.py", line 12, in
asyncio.run(main())
File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "myv.py", line 6, in main
vehicles = await client.list_vehicles()
File "/Kubernetes/tesla_api-master/tesla_api/init.py", line 119, in list_vehicles
return [Vehicle(self, vehicle) for vehicle in await self.get("vehicles")]
File "/Kubernetes/tesla_api-master/tesla_api/init.py", line 91, in get
await self.authenticate()
File "/Kubernetes/tesla_api-master/tesla_api/init.py", line 81, in authenticate
expiry_time = timedelta(seconds=self._token["expires_in"])
KeyError: 'expires_in'
I thought the module would authenticate or re-authenticate as needed? But the "expires_in key is missing.
Any help would be appreciated?
running python 3.7.3 on Raspbian 32-bit.
Hi there I wanted to install the tesla_api I think something is not working when the install compiles multdict on the orange pi
Works fine on windows. Armbian is updated as are python, pip, setuptools
pip -V
pip 20.1.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)
Running on an orangepi 512mb ram
root@orangepione:~# pip install tesla_api
Collecting tesla_api
Using cached tesla_api-2.0.1-py3-none-any.whl (7.3 kB)
Processing ./.cache/pip/wheels/4d/66/91/e897c13270a82fbbab0c7c03ee355685e534d46840b54ec107/aiohttp-2.3.10-py3-none-any.whl
Collecting multidict>=4.0.0
Using cached multidict-4.7.6.tar.gz (50 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing wheel metadata ... done
Collecting yarl>=1.0.0
Using cached yarl-1.4.2.tar.gz (163 kB)
Collecting async-timeout>=1.2.0
Using cached async_timeout-2.0.1-py3-none-any.whl (5.9 kB)
Processing ./.cache/pip/wheels/a9/0f/87/af29b8994a28856fb64c270177bbb6716da2690d07af2a2fb7/idna_ssl-1.1.0-py3-none-any.whl
Collecting chardet
Using cached chardet-3.0.4-py2.py3-none-any.whl (133 kB)
Collecting idna>=2.0
Using cached idna-2.9-py2.py3-none-any.whl (58 kB)
Building wheels for collected packages: multidict, yarl
Building wheel for multidict (PEP 517) ... error
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 /usr/local/lib/python3.5/dist-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmpv8ix86qb
cwd: /tmp/pip-install-iucd6923/multidict
Complete output (45 lines):
**********************
* Accellerated build *
**********************
running bdist_wheel
running build
running build_py
creating build
creating build/lib.linux-armv7l-3.5
creating build/lib.linux-armv7l-3.5/multidict
copying multidict/_multidict_py.py -> build/lib.linux-armv7l-3.5/multidict
copying multidict/_multidict_base.py -> build/lib.linux-armv7l-3.5/multidict
copying multidict/_compat.py -> build/lib.linux-armv7l-3.5/multidict
copying multidict/_abc.py -> build/lib.linux-armv7l-3.5/multidict
copying multidict/__init__.py -> build/lib.linux-armv7l-3.5/multidict
running egg_info
writing dependency_links to multidict.egg-info/dependency_links.txt
writing top-level names to multidict.egg-info/top_level.txt
writing multidict.egg-info/PKG-INFO
reading manifest file 'multidict.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files found matching 'multidict/_multidict.html'
warning: no previously-included files found matching 'multidict/*.so'
warning: no previously-included files found matching 'multidict/*.pyd'
warning: no previously-included files found matching 'multidict/*.pyd'
no previously-included directories found matching 'docs/_build'
writing manifest file 'multidict.egg-info/SOURCES.txt'
copying multidict/__init__.pyi -> build/lib.linux-armv7l-3.5/multidict
copying multidict/_multidict.c -> build/lib.linux-armv7l-3.5/multidict
copying multidict/py.typed -> build/lib.linux-armv7l-3.5/multidict
creating build/lib.linux-armv7l-3.5/multidict/_multilib
copying multidict/_multilib/defs.h -> build/lib.linux-armv7l-3.5/multidict/_multilib
copying multidict/_multilib/dict.h -> build/lib.linux-armv7l-3.5/multidict/_multilib
copying multidict/_multilib/istr.h -> build/lib.linux-armv7l-3.5/multidict/_multilib
copying multidict/_multilib/iter.h -> build/lib.linux-armv7l-3.5/multidict/_multilib
copying multidict/_multilib/pair_list.h -> build/lib.linux-armv7l-3.5/multidict/_multilib
copying multidict/_multilib/views.h -> build/lib.linux-armv7l-3.5/multidict/_multilib
running build_ext
building 'multidict._multidict' extension
creating build/temp.linux-armv7l-3.5
creating build/temp.linux-armv7l-3.5/multidict
arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c multidict/_multidict.c -o build/temp.linux-armv7l-3.5/multidict/_multidict.o -O2 -std=c99 -Wall -Wsign-compare -Wconversion -fno-strict-aliasing -pedantic
multidict/_multidict.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1
----------------------------------------
ERROR: Failed building wheel for multidict
Building wheel for yarl (setup.py) ... error
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-iucd6923/yarl/setup.py'"'"'; __file__='"'"'/tmp/pip-install-iucd6923/yarl/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-25i8b7oj
cwd: /tmp/pip-install-iucd6923/yarl/
Complete output (38 lines):
**********************
* Accellerated build *
**********************
running bdist_wheel
running build
running build_py
creating build
creating build/lib.linux-armv7l-3.5
creating build/lib.linux-armv7l-3.5/yarl
copying yarl/quoting.py -> build/lib.linux-armv7l-3.5/yarl
copying yarl/__init__.py -> build/lib.linux-armv7l-3.5/yarl
running egg_info
writing yarl.egg-info/PKG-INFO
writing dependency_links to yarl.egg-info/dependency_links.txt
writing requirements to yarl.egg-info/requires.txt
writing top-level names to yarl.egg-info/top_level.txt
reading manifest file 'yarl.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.cache' found anywhere in distribution
warning: no previously-included files found matching 'yarl/_quoting.html'
warning: no previously-included files found matching 'yarl/_quoting.*.so'
warning: no previously-included files found matching 'yarl/_quoting.pyd'
warning: no previously-included files found matching 'yarl/_quoting.*.pyd'
no previously-included directories found matching 'docs/_build'
writing manifest file 'yarl.egg-info/SOURCES.txt'
copying yarl/__init__.pyi -> build/lib.linux-armv7l-3.5/yarl
copying yarl/_quoting.c -> build/lib.linux-armv7l-3.5/yarl
copying yarl/_quoting.pyx -> build/lib.linux-armv7l-3.5/yarl
copying yarl/py.typed -> build/lib.linux-armv7l-3.5/yarl
running build_ext
building 'yarl._quoting' extension
creating build/temp.linux-armv7l-3.5
creating build/temp.linux-armv7l-3.5/yarl
arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c yarl/_quoting.c -o build/temp.linux-armv7l-3.5/yarl/_quoting.o
yarl/_quoting.c:4:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1
----------------------------------------
ERROR: Failed building wheel for yarl
Running setup.py clean for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict which use PEP 517 and cannot be installed directly
can I get battery data every one hour?
It appears that one of the endpoints to get info from list_energy_sites() endpoint has been deprecated.
# Simple code to demonstrate problem
from tesla_api import TeslaApiClient
from datetime import datetime
import time
now = datetime.now()
print(now)
print("Starting Tesla5 program...")
client = TeslaApiClient("username", "password")
energy_sites = client.list_energy_sites()
print("Number of energy sites = %d" % (len(energy_sites)))
assert(len(energy_sites)==1)
# Output
==================== RESTART: C:/Python/Powerwall/Tesla5B.py ===================
2021-01-30 10:28:55.929762
Starting Tesla5 program...
Traceback (most recent call last):
File "C:/Python/Powerwall/Tesla5B.py", line 11, in <module>
energy_sites = client.list_energy_sites()
File "C:/Python/Powerwall\tesla_api\__init__.py", line 94, in list_energy_sites
return [Energy(self, products['energy_site_id']) for products in self.get('products')]
File "C:/Python/Powerwall\tesla_api\__init__.py", line 69, in get
self.authenticate()
File "C:/Python/Powerwall\tesla_api\__init__.py", line 55, in authenticate
self._token = self._get_new_token()
File "C:/Python/Powerwall\tesla_api\__init__.py", line 33, in _get_new_token
raise AuthenticationError(response_json['response'])
tesla_api.AuthenticationError: Authentication to the Tesla API failed: endpoint_deprecated:_please_update_your_app.
>>>
Tesla has deprecated the /oauth/token endpoint in favor of using auth.tesla.com. It's been about 45 days since I initially started using this, so I suspect my original token has expired, and no longer able to get a new oauth token.
This appears to be discussed here https://tesla-api.timdorr.com/api-basics/authentication
Great module! Just what I'm looking for.
Works fine when I specify username & password, but when I tried to use a pre-existing token to create a client..
Throws 'TypeError: init() got an unexpected keyword argument 'token'
The source here suggests that this should work, and I've installed the latest version (pip install tesla-api). Python 3.5
Any ideas?
I'm trying to use commands like:
v.charge.get_state
v.controls.flash_lights()
But each time I get error messages from Python.
Can you provide some more working examples on how to use the various functions within those classes?
Would like to access the same endpoint through this API as is available via "Powerwall_ip_address/API/metres/aggregates"...cant' find it in energy.py nor have I been able to re-create.
All,
I am new in programming & using APIs.
I tried the example to connect by a python program on raspberry PI to my tesla but I get this error:
What is the problem... ?
Traceback (most recent call last):
File "/home/pi/Mijnprogs/Python/Basis python/Tesla_communication.py", line 15, in
asyncio.run(main())
File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "/home/pi/Mijnprogs/Python/Basis python/Tesla_communication.py", line 7, in main
vehicles = await client.list_vehicles()
File "/home/pi/.local/lib/python3.7/site-packages/tesla_api/init.py", line 104, in list_vehicles
return [_class(self, vehicle) for vehicle in await self.get('vehicles')]
File "/home/pi/.local/lib/python3.7/site-packages/tesla_api/init.py", line 80, in get
await self.authenticate()
File "/home/pi/.local/lib/python3.7/site-packages/tesla_api/init.py", line 68, in authenticate
expiry_time = timedelta(seconds=self.token['expires_in'])
KeyError: 'expires_in'
Traceback (most recent call last):
File "./test.py", line 32, in <module>
print(v.controls.flash_lights())
File "/usr/local/lib/python3.7/dist-packages/tesla_api/controls.py", line 22, in flash_lights
return self._api_client.post('vehicles/{}/command/flash_lights'.format(self._vehicle_id))
File "/usr/local/lib/python3.7/dist-packages/tesla_api/__init__.py", line 85, in post
raise ApiError(response_json['error'])
tesla_api.ApiError: Tesla API call failed: verify failed: crypto/rsa: verification error for txid `2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0`
Hi, total noob here, I'm trying to work out how to get the current charge level of the car to be shown in the terminal window, same as the display_name, vin, etc.
Thanks in advance!
if you have tesla vehicle as well as a solar/powerwall product, and you try to run the code in your readme file for pulling energy information it fails. I am not a good python programmer but it appears it is not able to parse the return correctly. I "fixed" it adding something like this to the init file.
async def list_energy_sites(self, _class=Energy):
d1, d2 = await self.get('products')
energy_id = d2['energy_site_id']
return [energy_id]
this will allow it to return an actual energy_site_id. I did the 2nd since it seems to always be the 2nd set of dictionary in my playing with it on postman. I converted the return to a list because a 2nd issue is then when the code from readme when to do len it couldnt. The convert addressed that.
now i am running into issue where i cant seem to pull any information about the site.
the line reserve = await energy_sites[0].get_backup_reserve_percent()
returns an error:
AttributeError: 'int' object has no attribute 'get_backup_reserve_percent'
this then continues down the entire list of other commands you provide in the readme.
Currently all the functions in the API use blocking requests. This means when writing an application using asyncio, the interface freezes and becomes unresponsive for the duration of each request.
I am getting the error below. Any suggestions?
Traceback (most recent call last):
File "/Users/jackkorber/Desktop/Python/GetPowerwallCapacity/powerwallCapacity.py", line 31, in
asyncio.run(main())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
return future.result()
File "/Users/jackkorber/Desktop/Python/GetPowerwallCapacity/powerwallCapacity.py", line 12, in main
energy_sites = await client.list_energy_sites()
File "/Users/jackkorber/Desktop/Python/GetPowerwallCapacity/tesla_api/init.py", line 123, in list_energy_sites
for product in await self.get("products") if "energy_site_id" in product]
File "/Users/jackkorber/Desktop/Python/GetPowerwallCapacity/tesla_api/init.py", line 91, in get
await self.authenticate()
File "/Users/jackkorber/Desktop/Python/GetPowerwallCapacity/tesla_api/init.py", line 81, in authenticate
expiry_time = timedelta(seconds=self._token["expires_in"])
KeyError: 'expires_in'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7fa22a881ac0>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7fa22a8a5520>, 0.69530855)]']
connector: <aiohttp.connector.TCPConnector object at 0x7fa22a881af0>
From time to time Tesla-API servers return text/html instead of application/json.
Which results in a rather nasty Exception (Some information is obfuscated):
File "/home/....../tesla_api/__init__.py", line 154, in get
response_json = await resp.json()
File "/home/....../lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 1026, in json
raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://owner-api.teslamotors.com/api/1/vehicles/21212121212121/data_request/charge_state')
raise ContentTypeError(
Handling this is the app seems too complicated, as this error could occur at any point the app code (and api call) and just generate a lot of copy & paste code for exception handling. Or a 2nd api layer around the lib just to handle those rare hick-ups.
The lib could retry to send the command for a defined number of times or raise a CommunicationError Exception of some sort.
A few weeks ago Tesla introduced MFA (Multi Factor Authentication) which essentially breaks this lib when the Tesla customer has MFA activated. Please fix.
If the login credentials are empty strings, it hits this error instead of the normal AuthenticationError:
Traceback (most recent call last):
File "tesla.py", line 42, in on_login
vehicles = self.client.list_vehicles()
File "/usr/local/lib/python3.6/dist-packages/tesla_api/__init__.py", line 90, in list_vehicles
return [Vehicle(self, vehicle) for vehicle in self.get('vehicles')]
File "/usr/local/lib/python3.6/dist-packages/tesla_api/__init__.py", line 68, in get
self.authenticate()
File "/usr/local/lib/python3.6/dist-packages/tesla_api/__init__.py", line 56, in authenticate
expiry_time = timedelta(seconds=self._token['expires_in'])
KeyError: 'expires_in'
Many thanks for your work with this project
I have an issue with using set_charge_limit(percentage) in class Charge:
Whenever value provided between 50-100, the vehicle is set to 50%, but no error is returned.
I would like to set the vehicle for example to 95%
Does it work for you or is there an issue?
Many thanks in advance for your help
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.