Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tesla Integration via official vehicle-command library #10460

Closed
lgleim opened this issue Oct 23, 2023 · 44 comments · Fixed by #10802
Closed

Tesla Integration via official vehicle-command library #10460

lgleim opened this issue Oct 23, 2023 · 44 comments · Fixed by #10802
Labels
backlog Things to do later

Comments

@lgleim
Copy link

lgleim commented Oct 23, 2023

Is your feature request related to a problem? Please describe.
Tesla has announced deprecating HTTP REST APIs, which is expected to affect owners starting in 2024 and will likely break unofficial APIs and their wrappers like the currently used https://github.com/bogosj/tesla library.

Describe the solution you'd like
Reimplement Tesla Vehicle support via the official https://github.com/teslamotors/vehicle-command library.

Describe alternatives you've considered
Continue using unofficial APIs or hope they will (or make them) update to wrapping the official Tesla API.

Additional context
https://developer.tesla.com/docs/fleet-api#2023-10-02-tesla-vehicle-command-sdk

@andig
Copy link
Member

andig commented Oct 24, 2023

Afaikt using the Tesla API requires you to run your own Domain and provide a certificate. That does not sound doable for most users. Is this perception wrong?
That said, I‘ve applied for developer account but have not received approval…

If anyone has access and time to spend I‘d be happy to support a PR.

@lgleim
Copy link
Author

lgleim commented Oct 24, 2023

It does not require Domain name nor Domain certificate unless you decided to run the included REST proxy on a public domain.

The public-private key pair talked about in the README is directly used to sign (and possibly encrypt) messages similar to how PGP uses cryptography. The library even includes its own keygen tool to make key generation (and subsequent registration in your Tesla vehicle's keychain) simple.

Some developers may be familiar with Tesla's Owner API. Owner API will stop working as vehicles begin requiring end-to-end command authentication.

Looks like Tesla is fully depreciating public REST servers in favor of their new protocol.

Tesla vehicles now support a protocol that provides end-to-end command authentication.

The https://github.com/teslamotors/vehicle-command directly implements this protocol

This Golang package uses the new protocol to control vehicle functions, such as climate control and charging.

The golang library can either be used directly, via a command-line tool, or via a local REST service (which both use the library internally).

Looks like all newer Tesla models will need to be switched to the new protocol. Only:

Pre-2021 Model S and X vehicles will continue to support the full REST API, and do not support the new protocol.

@andig

This comment was marked as resolved.

@andig andig added the enhancement New feature or request label Oct 26, 2023
@andig
Copy link
Member

andig commented Oct 26, 2023

It does not require Domain name nor Domain certificate unless you decided to run the included REST proxy on a public domain.

Its still unclear to me how this should work from user side. Where does the user obtain the token? Does he need to register a developer account?

Ist aber vllt. einfach wenn wir auf Deutsch reden ;)

@lgleim
Copy link
Author

lgleim commented Oct 26, 2023

Klar. Von der Nutzerseite würde das so aussehen, dass man sich ein public/private key-pair generiert und den public key direkt in der keychain des Teslas hinterlegt. Also genauso wie man das z.B. mit einem SSH public/private keypair macht. Mit dem private key kann der lokale client dann Nachrichten signieren (und in der Theorie auch verschlüsseln, dafür würde man aber normalerweise dann aus Effizienzgründen symmetrische Verschlüsslung nutzen).

Der oauth token wird zusätzlich gebraucht. Das ist quasi unverändert genauso wie bis jetzt. Allerdings ist natürlich eine wichtige Frage ob in Zukunft nur noch Tesla's 3rd party tokens akzeptiert werden, die man über das Developer portal anlegt. Details dazu hier unter Setup.
Leider sieht das aber nach einem bevorstehenden Cash-grab auf seiten von Tesla aus.
image

Ich schreibe im Anschluss mal eine Mail an fleetapisupport@tesla.com und frage nach Feedback wie die in Zukunft mit open source Projekten und inoffiziellen oauth tokens umgehen wollen.

@andig

This comment was marked as resolved.

@lgleim
Copy link
Author

lgleim commented Oct 26, 2023

In der Tat muss man sich leider nun einen Partner Account registrieren, bekommt dann einen partner OAuth token, und muss dann einen generierten public key unter einer eigenen (partner) domain hosten.
Zusätzlich braucht es dann noch einen mit dem partner-token erstellten client token, der dann zugriff auf die tatsächliche vehicle API gibt (dafür braucht es dann aber keinen server mehr). Im Ergebnis müsste entweder jeder User zukünftig durch den ganzen Prozess laufen, oder aber EVCC.io als Telsa Partner agieren...

@lgleim
Copy link
Author

lgleim commented Oct 26, 2023

Konkrete Möglichkeit bei der jeder Nutzer unabhängig bleibt könnte wahrscheinlich wie folgt aussehen:

  1. User registriert einen Partneraccount unter https://developer.tesla.com/ und erhält clientID und clientSecret. Zusätzlich nutzt er seinen Github Account (im Folgenden Github username "mynick").
    1. App name, Description und Purpose nach Belieben
    2. origin, redirect und return URL werden alle auf https://mynick.github.io (oder eine variation) gesetzt (dient als Domain des Partners)
    3. Als API scope wird Vehicle Charging Management ausgewählt
  2. Mittels tesla-keygen create (oder ssh-keygen etc.) wird eine public/private keypair erzeugt
  3. Der public key wird wie hier beschrieben auf github pages unter https://mynick.github.io/.well-known/appspecific/com.tesla.3p.public-key.pem abgelegt
  4. Der User generiert nun einen partner authentication token
  5. Mit dem partner token wird nun der public key (https://mynick.github.io/.well-known/appspecific/com.tesla.3p.public-key.pem) via https://developer.tesla.com/docs/fleet-api#register in der Tesla Cloud registriert.
  6. Der User geht nun auf https://tesla.com/_ak/mynick.github.io was die Tesla App öffnet und um nach Bestätigung den public key von mynick in den keystore des Teslas von User importiert. Alternativ geht dies scheinbar auch lokal via Bluetooth
  7. Ab dann können anscheinend mit dem lokalen private key (in Schritt 2 erstellt) Befehle per Bluetooth direkt an das Auto gesendet werden. Beispiel aus der README von vehicle-command:
    tesla-control -ble -key-file private_key.pem lock
    Falls das wirklich so funktioniert sollte der Private key in jedem Falle nicht zwischen evcc usern geteilt werden (macht auch irgendwie Sinn für einen private key)
  8. Um Befehle nicht nur per Bluetooth sondern auch via IP senden zu können muss zusätzlich ein zweites customer OAuth token erzeugt werden, vermutlich mit scope vehicle_charging_cmds. Gemeinsam mit customer token und private key sollten dann endlich auch Befehle direkt Internet gesendet werden können.

Soweit die Theorie. Prinzipiell auch alles automatisierbar. Aber...

@lgleim

This comment was marked as resolved.

@RTTTC

This comment was marked as resolved.

@andig

This comment was marked as resolved.

@vtml

This comment was marked as off-topic.

@andig andig added backlog Things to do later and removed enhancement New feature or request labels Nov 4, 2023
@andig

This comment was marked as resolved.

@changyang1230
Copy link

changyang1230 commented Dec 12, 2023

Hi there, I tried looking around and this seems to be the most relevant issue page for the Tesla's API deprecation.

One of the cloud softwares "ChargeHQ" which performs similar function as EVCC (but via third party cloud rather than self-hosting) has updated to the new Tesla system.

I am wondering if this is already addressed in EVCC? Or whether it's not going to be solvable in EVCC given the requirement for hosted certificate etc (judging from the conversation above).

Thanks.

Link to the relevant discussion in Charge HQ:
https://chargehq.net/kb/how-does-the-tesla-third-party-app-connection-work

@andig
Copy link
Member

andig commented Dec 13, 2023

See #10802, this should already work (but not yet and potentially never for TWC integration).

@litithio
Copy link

Gibt es einen groben Zeitrahmen, bis wann die neue API integriert sein wird?
Ich habe seit Mitte November 2023 ein Tesla Model 3 2024/Highland, welches offenbar bereits nur noch über das neue API kommuniziert. Da ich als Wallbox einen TWC3 einsetze, ist EVCC für mich leider aktuell gar nicht sinnvoll nutzbar.
Ich bin jetzt vorerst auf Tesla Solar Charger ausgewichen, welcher die Ladung über das API von Teslamate steuert. Das funktioniert auch soweit, aber leider kann es in Sachen Funktionalität und UI nicht wirklich mit EVCC mithalten.

@andig
Copy link
Member

andig commented Jan 12, 2024

Da ich als Wallbox einen TWC3 einsetze, ist EVCC für mich leider aktuell gar nicht sinnvoll nutzbar.

Das ist eine Sondersituation die wir nicht OOTB lösen können. Steuern über das neue API ist nur möglich wenn es einen private key gibt. Den können wir natürlich nicht rausgeben, d.h. jeder Anwender müsste sich selbst die entsprechenden Accounts bei Tesla besorgen und Keys erzeugen. Im Code ist das aktuell nicht berücksichtigt, könnte aber eingebaut werden.

@litithio falls Du Dir selbst einen Tesla Partneraccount besorgen willst könnten wir dann zusammen schauen, wie der zu integrieren wäre. Ohne geht es nicht :/

Ergänzung: Davon unabhängig ist es mit dem PR bereits möglich, Daten vom Fahrzeug abzufragen!

@litithio
Copy link

Ich hatte mir über tesla.evcc.io bereits einen Token generiert und die evcc.yaml eingetragen. Der Datenabruf war damit wie du sagst bereits möglich. Ansteuerung des Fahrzeugs leider nicht, fehlt vermutlich noch das passende Template und der damit verbundene Code.
Du weißt nicht zufällig wie es bei Tesla Solar Charger gelöst ist? Hier Funktioniert ja die Steuerung über das neue API. Die Verbindung zu Tesla erfolgt hier über das API von Teslamate.

Ich bin gerne bereit mir einen Partneraccount zu besorgen und Versuchskaninchen zu spielen, falls man dafür nicht irgendwie speziellen Voraussetzungen erfüllen muss. Hast du einen Link für mich wo ich das beantragen/mich registrieren kann?

@andig
Copy link
Member

andig commented Jan 12, 2024

Du weißt nicht zufällig wie es bei Tesla Solar Charger gelöst ist?

Kenne ich gar nicht.

Hast du einen Link für mich wo ich das beantragen/mich registrieren kann?

Siehe https://github.com/teslamotors/vehicle-command. Ist allerdings mühsam...

@Hooch76
Copy link

Hooch76 commented Jan 12, 2024

Kenne ich gar nicht.

https://github.com/pkuehnel/TeslaSolarCharger

@litithio
Copy link

Siehe https://github.com/teslamotors/vehicle-command. Ist allerdings mühsam...

Ich brauche dafür einen Developer Account, sehe ich das richtig? Da steht, die Registrierung muss auf ein Unternehmen erfolgen, und man muss dabei eine valide Steuernummer angeben.
Das hätte ich jetzt nicht parat. Oder brauche ich den Developer Account gar nicht?

@andig
Copy link
Member

andig commented Jan 13, 2024

Den brauchst du...

@litithio
Copy link

Ich glaube das übersteigt leider meine Möglichkeiten ....
Ich habe noch mal etwas geschaut und hier führt Tesla Solar Charger die Unterstützung für das Fleet API ein:

https://github.com/pkuehnel/TeslaSolarCharger/releases/tag/v2.23.0

Vielleicht lassen sich Erkenntnisse daraus ziehen, wie das auch in evcc umsetzbar wäre?

@infinus
Copy link
Contributor

infinus commented Jan 23, 2024

@andig I'd be willing to create a developer account under my name/tax ID. Tesla seems to only allow unique application names. Do you want me to create one for evcc.io or do you want me to make one for a domain I control for testing purposes?

It says the public key must be be placed in the /.well-known section of the application website do we have that ability with the evcc.io site?

More details if needed:
A PEM-encoded EC public key using the secp256r1 curve (prime256v1) must be hosted at https:///.well-known/appspecific/com.tesla.3p.public-key.pem. This public key will be registered on devices and used to validate commands that are generated by the vehicle-command proxy.
The domain will be displayed to users as part of the mobile-app-based vehicle key-pairing process.

@andig
Copy link
Member

andig commented Jan 24, 2024

@infinus it would help to test the draft PR.

Do you want me to create one for evcc.io or do you want me to make one for a domain I control for testing purposes?

For what purpose?

@yipikaye

This comment was marked as off-topic.

@naltatis

This comment was marked as off-topic.

@infinus
Copy link
Contributor

infinus commented Jan 24, 2024

@andig ill just create one for evcc.io

it is asking for the following:

The whitelisted URI that the user is redirected to after they have successfully authenticated. This URI is the endpoint in your application that handles exchanging a code granted by Tesla OAuth for an access token.
V Use a valid URL structure containing the path
Ex:
https://example.sample.com/path
Ex: myapp://app/path

@yipikaye
Copy link

@infinus Once you figure this out (it sounds like you're close) can you share what you did in this thread? I am also willing to setup a developer account and support the effort in this thread.

@naltatis
Copy link
Member

naltatis commented Jan 24, 2024

💪 @andig merged the implementation for the new API today, and we've just published nightly builds for all platforms where our Tesla integration works again. Here is what you have to do 👇

How to get Tesla Integration working?

  1. generate a new pair of API tokens here https://tesla.evcc.io
  2. switch to the latest nightly build of evcc
  3. change your template from tesla to tesla-command.
vehicles:
 - name: mytesla
   type: template
-  template: tesla
+  template: tesla-command
   accessToken: [...] # generetad by tesla.evcc.io
   refreshToken:  [...] # generetad by tesla.evcc.io
   ...

⚠️ The template name tesla-command might change before the next stable release. But for now, this is the working version.

Using local builds is still possible, but now requires a Tesla Developer account. Use the TESLA_CLIENT_ID env.

@infinus
Copy link
Contributor

infinus commented Jan 24, 2024

I updated to the nightly and made the changes above and granted cvcc all permissions. I get an error and charge control is not working.

creating vehicle Infinus failed: cannot create vehicle type 'template': cannot create vehicle type 'tesla-command': cannot get vehicles: unexpected status: 421 (Misdirected Request)

Vehicle not capable of charge control error on front end.

@andig
Copy link
Member

andig commented Jan 24, 2024

Lets please not confuse things here. PR is finished and merged. It allows reading the Tesla again. It does NOT allow controlling it- that's entirely different story.

For what is merged, no developer account is required. One thing we've not (yet) done is look at different fleet APIs. Code uses EU. Not sure what other vehicles, e.g. in Australia, would use...

@infinus
Copy link
Contributor

infinus commented Jan 24, 2024

I was going to say that from my end I see no difference in the nightly vs prior ones but maybe that is because I'm based in the US so the fact that this code uses EU probably explains why!

You can query the users region and appropriate fleet-api URL so you should be able to dynamically assign it, this should save you a lot of posts from non-eu users.
https://developer.tesla.com/docs/fleet-api?shell#region

@yipikaye
Copy link

yipikaye commented Jan 24, 2024

Hi @andig ,
I follow about read working now, I'm offering to support with a developer account for TWC3 (vehicle control) as I was one of those people who got TWC3 not knowing it was dumb :( I have a contractor coming to quote to install a SMA charger to go with my battery and solar.

I can also test the Australian region.

I have seen now some home automation uses open source and no developer account so maybe there are other implementations too.

@andig
Copy link
Member

andig commented Jan 25, 2024

I was going to say that from my end I see no difference in the nightly vs prior ones but maybe that is because I'm based in the US so the fact that this code uses EU probably explains why!

@infinus did you even configure the new integration? "Prior" it didn't even exist so that makes me suspect you're just continuing with the old config.

I can also test the Australian region.

@yipikaye please do so. For now "can I get the soc from my Tesla". Controlling it- I repeat- is a different topic and new discussion. That said: waiting for cross-region feedback including trace log, please open new issue if not working.

I have seen now some home automation uses open source and no developer account so maybe there are other implementations too.

What we've done sofar does NOT require a custom dev account- it is using the evcc one.

@yipikaye
Copy link

Sure thing, I couldn't see a separate issue for TWC3 not working. Is there an existing thread we can continue this discussion or would you prefer I create a new one?

I follow the not needing dev account now. But I was looking forward to fixing TWC 3.

@yipikaye
Copy link

I created the following feature request

#11846

@infinus
Copy link
Contributor

infinus commented Jan 25, 2024

I was going to say that from my end I see no difference in the nightly vs prior ones but maybe that is because I'm based in the US so the fact that this code uses EU probably explains why!

@infinus did you even configure the new integration? "Prior" it didn't even exist so that makes me suspect you're just continuing with the old config.

Yes, I did. I generated a new access token on the site and granted all permissions and updated the evcc.yaml with the new access and refresh tokens

vehicles:
- name: Infinus
  type: template
  template: tesla-command
  accessToken:  ###
  refreshToken: ###

I was previously on 0.123.3 and updated to 0.123.9 and started getting errors in the logs like this:

creating vehicle Infinus failed: cannot create vehicle type 'template': cannot create vehicle type 'Tesla'

I assumed this was due to the API change as the yaml had not changed between versions.

I updated to nightly and made the changes and now the error says this:

creating vehicle Infinus failed: cannot create vehicle type 'template': cannot create vehicle type 'tesla-command': cannot get vehicles: unexpected status: 421 (Misdirected Request)

I looked up up similar examples online I found that Tesla API will return misdirected request if the request is to the wrong region. If you send to the base url instead of the EU region it should reply with the correct code:

Server returned 421: Misdirected Request: {"response":null,"error":"user out of region, use base URL: https://fleet-api.prd.na.vn.cloud.tesla.com, see https://developer.tesla.com/docs/fleet-api#regional-requirements","error_description":""}

so it seems to me updating the url to https://fleet-api.prd.na.vn.cloud.tesla.com should make it compatible with all regions as using the base URL should return the region specific URL.

@Sammy990
Copy link

When I try to generate the tokens on the new website, I always get the following error from the evcc site after I selected all permissions and clicking on allow:

insufficient scopes: missing token scopes

Any idea what I'm doing wrong?

@andig
Copy link
Member

andig commented Jan 27, 2024

Guess I broke that, will fix today.

@yipikaye
Copy link

yipikaye commented Feb 1, 2024

@andig @infinus I can confirm the tesla-command template is working in Australia for both the stable and nightly build.

One small gotcha, the token expires pretty fast, I got distracted and the token had expired before I could add it.

@braeunli
Copy link

braeunli commented Feb 5, 2024

Was muss ich tun, dass es wieder funktioniert? Habe bereits die beiden Token aktualisiert, leider ohne Erfolg.

@litithio
Copy link

litithio commented Feb 5, 2024

Warten.
Die Steuerung des Autos über das neue API ist Stand jetzt noch nicht implementiert.

@andig
Copy link
Member

andig commented Feb 5, 2024

Worum es in diesem Issue auch gar nicht geht... geschlossen da off-topic.

@evcc-io evcc-io locked as off-topic and limited conversation to collaborators Feb 5, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
backlog Things to do later
Projects
None yet
Development

Successfully merging a pull request may close this issue.