Giter Club home page Giter Club logo

tesla's Introduction

tesla

wercker status

This library provides a wrapper around the API to easily query and command the a Tesla Model S remotely in Go.

Library Documentation

https://godoc.org/github.com/jsgoecke/tesla

API Documentation

View Tesla JSON API Documentation

This is unofficial documentation of the Tesla JSON API used by the iOS and Android apps. The API provides functionality to monitor and control the Model S (and future Tesla vehicles) remotely. The project provides both a documention of the API and a Go library for accessing it.

Installation

go get github.com/jsgoecke/tesla

Tokens

You may get your tokens to use as client_id and client_secret here.

Usage

Here's an example (more in the /examples project directory):

func main() {
	client, err := tesla.NewClient(
		&tesla.Auth{
			ClientID:     os.Getenv("TESLA_CLIENT_ID"),
			ClientSecret: os.Getenv("TESLA_CLIENT_SECRET"),
			Email:        os.Getenv("TESLA_USERNAME"),
			Password:     os.Getenv("TESLA_PASSWORD"),
		})
	if err != nil {
		panic(err)
	}

	vehicles, err := client.Vehicles()
	if err != nil {
		panic(err)
	}

	vehicle := vehicles[0]
	status, err := vehicle.MobileEnabled()
	if err != nil {
		panic(err)
	}

	fmt.Println(status)
	fmt.Println(vehicle.HonkHorn())

	// Autopark
	// Use with care, as this will move your car
	vehicle.AutoparkForward()
	vehicle.AutoparkReverse()
	// Use with care, as this will move your car

	// Stream vehicle events
	eventChan, errChan, err := vehicle.Stream()
	if err != nil {
		fmt.Println(err)
		return
	} else {
		for {
			select {
			case event := <-eventChan:
				eventJSON, _ := json.Marshal(event)
				fmt.Println(string(eventJSON))
			case err = <-errChan:
				fmt.Println(err)
				if err.Error() == "HTTP stream closed" {
					fmt.Println("Reconnecting!")
					eventChan, errChan, err := vehicle.Stream()
					if err != nil {
						fmt.Println(err)
						return
					}
				}
			}
		}
	}
}

Examples

Pull Requests

I appreciate all the pull requests to date, and have merged them when I can. I would kindly ask going forward if you do send a PR, please ensure it has the corresponding unit test, or unit test change, that passes. I have tried to write tests after the fact, but that is not best practice. Thank you!

Credits

Thank you to Tim Dorr who did the heavy lifting to document the Tesla API and also created the model-s-api Ruby Gem.

Copyright & License

Copyright (c) 2016-Present Jason Goecke. Released under the terms of the MIT license. See LICENSE for details.

tesla's People

Contributors

codelingobot avatar dbrouwer-sbp avatar dewski avatar jnoxon avatar jsgoecke avatar mgb avatar think-free avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tesla's Issues

Regular EOFs on Stream that require client to add reconnect logic

    for {
        eventChan, err := vehicle.Stream()
        if err == nil {
            for {
                event := <-eventChan
                                if event != nil {
                                        log.Println(event)
                } else {
                    log.Println("EOF!")
                    break
                }
            }
        }
        log.Println("Reconnecting!")
    }

2016/06/01 01:16:16 Event -> Id: 1072e5e0-0b4b-4826-78c3-369871488e3d ShiftState:
2016/06/01 01:17:16 EOF!
2016/06/01 01:17:16 Reconnecting!
2016/06/01 01:17:20 Event -> Id: 1ff24e0a-8d8f-4871-5fce-2d7b3175a20c ShiftState:
2016/06/01 01:18:20 EOF!
2016/06/01 01:18:20 Reconnecting!
2016/06/01 01:18:22 Event -> Id: 4dca7baa-0e65-42cb-63cd-bf5e0331d084 ShiftState:
2016/06/01 01:19:22 EOF!
2016/06/01 01:19:22 Reconnecting!
2016/06/01 01:19:24 Event -> Id: 2776fe91-3b68-4dbe-7419-a9c41a408c57 ShiftState:

Need to grok this to understand how it handles EOF:

https://github.com/franela/goreq

"cause you can avoid common errors like EOF on stream and you could learn more about how to create your own http request library."

SetTemperature defaulting passenger and driver temperature to "LOW"

Not sure if this is just an issue with the model 3, but when setting the temperature via the command and putting the proper temperature in celcius the car sets the temperature to "LOW" which is 15 degrees C. Can you confirm this is working on the model s, or is this perhaps a change to the API? Currently researching, but don't have access to a model s to compare against.

Add defrost support

%@/api/1/vehicles/%@/command/front_defrost_on
%@/api/1/vehicles/%@/command/front_defrost_off
%@/api/1/vehicles/%@/command/rear_defrost_on
%@/api/1/vehicles/%@/command/rear_defrost_off

tesla Bluetooth control

I want to control the Tesla via Bluetooth (using it as a key) through an app I developed. So you can get on the car without feeling it, and I want to get these Bluetooth protocols. I wonder if I can get help. At present, there are already similar products on the Appstore, and this can be done.

Bad message from Tesla API stream

  • testing the example code from README
  • had to add some _ = eventChan etc to avvoid annoying compiler errors
  • using client secret and ID from upstream as the ones linked in README gave 401s

output:

λ echo $TESLA_CLIENT_SECRET                                                                                              
c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3
λ echo $TESLA_CLIENT_SECRET2
c75f14bbadc8bee3a7594412c31416f8300256d7668ea7e6e7f06727bfb9d220
λ go run ./teslago.go       
true
<nil>
Bad message from Tesla API stream
Bad message from Tesla API stream
Bad message from Tesla API stream
Bad message from Tesla API stream
Bad message from Tesla API stream
Bad message from Tesla API stream
Bad message from Tesla API stream
HTTP stream closed
Reconnecting!
^Csignal: interrupt
λ 

Screenshot of Safari (16-06-2020, 15-47-16)

tips?

vehicle_id must be int64

Running on Raspi Zero errors:

[main  ] FATAL 2021/01/25 07:44:05 cannot create vehicle 'tesla': cannot create type 'tesla': json: cannot unmarshal number 156374561234 into Go struct field .response.vehicle_id of type int

This

VehicleID int `json:"vehicle_id"`
should probably by an int64?

User reported this when running https://github.com/andig/evcc

How can I abort summon

Hi @jsgoecke

I was able to get the commands for autopark_forward and autopark_reverse from your repo. I forked timdorr's repo and added the functions for these two as shown below. It works fine. But I could not figure out how to abort/stop the summon. I dont know how to sniff the packets on the phone app. Do you know what command and parameters are sent when summon is stopped?

Thanks
John

def autopark_forward
ds = nil
while ds.nil? do
ds = drive_state
end
lat= ds['latitude']
lon = ds['longitude']
vid = id
action = 'start_forward'
command("autopark_request", body: {vehicle_id: id, lat: lat, lon: lon, action: action})
end

Commands return 403 - Forbidden

Hey,

I can succesfully login and retrieve vehicle information, but as soon as I want to send a command like start charging or lock doors, I get "403 Forbidden".

I created the access_token and refresh_token via the iOS App "Auth for Tesla".

Do I need something else?

Example Code:

c, err := tesla.NewClient(ctx, tesla.WithTokenFile(tokenPath))
	if err != nil {
		return err
	}

	vehicles, err := c.Vehicles()
	if err != nil {
		return err
	}

	for i, v := range vehicles {
		if i > 0 {
			fmt.Println("----")
		}

		wakeup, err := v.Wakeup()
		if err != nil {
			fmt.Println("Wake up err")
			fmt.Println(err)
		}

		fmt.Println(wakeup)

		fmt.Printf("ID: %x\n", v.ID)
		fmt.Printf("Name %s\n", v.DisplayName)

		enabled, err := v.MobileEnabled()
		fmt.Println(enabled) <--- True
		if err != nil {
			fmt.Println("mobile enabled err")
			fmt.Println(err)
		}

		err = v.LockDoors() <--- 403 Forbidden
		if err != nil {
			return err
		}

Thanks for your help!

502 Bad Gateway

I'm running

    client, err := tesla.NewClient(
        &tesla.Auth{
            ClientID:     "...",
            ClientSecret: "...",
            Email:        "...",
            Password:     "...",
        })
    if err != nil {
        logf("NewClient(...): %v, %v", client, err)
        panic(err)
    }

    vehicles, err := client.Vehicles()
    if err != nil {
        logf("Vehicles(): %v, %v", vehicles, err)
        panic(err)
    }

    if len(vehicles) != 1 {
        logf("not exactly 1 vehicle")
        panic("not exactly 1 vehicle")
    }

    vehicle := vehicles[0]
    status, err := vehicle.MobileEnabled()
    if err != nil {
        logf("MobileEnabled(): %v, %v", status, err)
        panic(err)
    }

where I get the following log output:

MobileEnabled(): false, 502 Bad Gateway

Any idea if I'm doing something wrong, or if Tesla changed their API again?

Stream crashes when an incomplete event is received

2016/06/01 01:29:42 EOF!
2016/06/01 01:29:42 Reconnecting!
2016/06/01 01:29:45 Event -> Id: 27588495-f09e-4ed8-5f0d-7a3f17358513 ShiftState:
2016/06/01 01:30:45 EOF!
2016/06/01 01:30:45 Reconnecting!
panic: runtime error: index out of range

goroutine 148 [running]:
panic(0x82f560, 0xc82000a070)
/usr/local/opt/go/libexec/src/runtime/panic.go:481 +0x3e6
github.com/jsgoecke/tesla.parseStreamEvent(0xc820429e80, 0x1a, 0x1a)
/Users/jgoecke/Dropbox/Development/go/src/github.com/jsgoecke/tesla/stream.go:69 +0x482
github.com/jsgoecke/tesla.readStream(0xc8203be090, 0xc820386ae0)
/Users/jgoecke/Dropbox/Development/go/src/github.com/jsgoecke/tesla/stream.go:57 +0x1af
created by github.com/jsgoecke/tesla.Vehicle.Stream
/Users/jgoecke/Dropbox/Development/go/src/github.com/jsgoecke/tesla/stream.go:44 +0x258

[Question] Powerwall Applicability

Hi @jsgoecke,

I was wondering if you have any insight into how adaptable this library could be for controlling a Tesla Powerwall. What would be the challenges with that endeavour?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.