tesla

package module
v0.0.0-...-e02ebd2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2020 License: MIT Imports: 10 Imported by: 10

README

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 (c) 2016-Present Jason Goecke. Released under the terms of the MIT license. See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	AuthURL      = "https://owner-api.teslamotors.com/oauth/token"
	BaseURL      = "https://owner-api.teslamotors.com/api/1"
	ActiveClient *Client
)
View Source
var (
	StreamParams = "speed,odometer,soc,elevation,est_heading,est_lat,est_lng,power,shift_state,range,est_range,heading"
	StreamingURL = "https://streaming.vn.teslamotors.com"
)

Functions

This section is empty.

Types

type Auth

type Auth struct {
	GrantType    string `json:"grant_type"`
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	Email        string `json:"email"`
	Password     string `json:"password"`
	URL          string
	StreamingURL string
}

Required authorization credentials for the Tesla API

type AutoParkRequest

type AutoParkRequest struct {
	VehicleID int     `json:"vehicle_id,omitempty"`
	Lat       float64 `json:"lat"`
	Lon       float64 `json:"lon"`
	Action    string  `json:"action,omitempty"`
}

Required elements to POST an Autopark/Summon request for the vehicle

type ChargeState

type ChargeState struct {
	ChargingState               string      `json:"charging_state"`
	ChargeLimitSoc              int         `json:"charge_limit_soc"`
	ChargeLimitSocStd           int         `json:"charge_limit_soc_std"`
	ChargeLimitSocMin           int         `json:"charge_limit_soc_min"`
	ChargeLimitSocMax           int         `json:"charge_limit_soc_max"`
	ChargeToMaxRange            bool        `json:"charge_to_max_range"`
	BatteryHeaterOn             bool        `json:"battery_heater_on"`
	NotEnoughPowerToHeat        bool        `json:"not_enough_power_to_heat"`
	MaxRangeChargeCounter       int         `json:"max_range_charge_counter"`
	FastChargerPresent          bool        `json:"fast_charger_present"`
	FastChargerType             string      `json:"fast_charger_type"`
	BatteryRange                float64     `json:"battery_range"`
	EstBatteryRange             float64     `json:"est_battery_range"`
	IdealBatteryRange           float64     `json:"ideal_battery_range"`
	BatteryLevel                int         `json:"battery_level"`
	UsableBatteryLevel          int         `json:"usable_battery_level"`
	BatteryCurrent              interface{} `json:"battery_current"`
	ChargeEnergyAdded           float64     `json:"charge_energy_added"`
	ChargeMilesAddedRated       float64     `json:"charge_miles_added_rated"`
	ChargeMilesAddedIdeal       float64     `json:"charge_miles_added_ideal"`
	ChargerVoltage              interface{} `json:"charger_voltage"`
	ChargerPilotCurrent         interface{} `json:"charger_pilot_current"`
	ChargerActualCurrent        interface{} `json:"charger_actual_current"`
	ChargerPower                interface{} `json:"charger_power"`
	TimeToFullCharge            float64     `json:"time_to_full_charge"`
	TripCharging                interface{} `json:"trip_charging"`
	ChargeRate                  float64     `json:"charge_rate"`
	ChargePortDoorOpen          bool        `json:"charge_port_door_open"`
	MotorizedChargePort         bool        `json:"motorized_charge_port"`
	ScheduledChargingStartTime  interface{} `json:"scheduled_charging_start_time"`
	ScheduledChargingPending    bool        `json:"scheduled_charging_pending"`
	UserChargeEnableRequest     interface{} `json:"user_charge_enable_request"`
	ChargeEnableRequest         bool        `json:"charge_enable_request"`
	EuVehicle                   bool        `json:"eu_vehicle"`
	ChargerPhases               interface{} `json:"charger_phases"`
	ChargePortLatch             string      `json:"charge_port_latch"`
	ChargeCurrentRequest        int         `json:"charge_current_request"`
	ChargeCurrentRequestMax     int         `json:"charge_current_request_max"`
	ManagedChargingActive       bool        `json:"managed_charging_active"`
	ManagedChargingUserCanceled bool        `json:"managed_charging_user_canceled"`
	ManagedChargingStartTime    interface{} `json:"managed_charging_start_time"`
}

Contains the current charge states that exist within the vehicle

type Client

type Client struct {
	Auth  *Auth
	Token *Token
	HTTP  *http.Client
}

Provides the client and associated elements for interacting with the Tesla API

func NewClient

func NewClient(auth *Auth) (*Client, error)

Generates a new client for the Tesla API

func NewClientWithToken

func NewClientWithToken(auth *Auth, token *Token) (*Client, error)

NewClientWithToken Generates a new client for the Tesla API using an existing token

func (Client) TokenExpired

func (c Client) TokenExpired() bool

TokenExpired indicates whether an existing token is within an hour of expiration

func (*Client) Vehicles

func (c *Client) Vehicles() (Vehicles, error)

Fetches the vehicles associated to a Tesla account via the API

type ClimateState

type ClimateState struct {
	InsideTemp              float64     `json:"inside_temp"`
	OutsideTemp             float64     `json:"outside_temp"`
	DriverTempSetting       float64     `json:"driver_temp_setting"`
	PassengerTempSetting    float64     `json:"passenger_temp_setting"`
	LeftTempDirection       float64     `json:"left_temp_direction"`
	RightTempDirection      float64     `json:"right_temp_direction"`
	IsAutoConditioningOn    bool        `json:"is_auto_conditioning_on"`
	IsFrontDefrosterOn      bool        `json:"is_front_defroster_on"`
	IsRearDefrosterOn       bool        `json:"is_rear_defroster_on"`
	FanStatus               interface{} `json:"fan_status"`
	IsClimateOn             bool        `json:"is_climate_on"`
	MinAvailTemp            float64     `json:"min_avail_temp"`
	MaxAvailTemp            float64     `json:"max_avail_temp"`
	SeatHeaterLeft          int         `json:"seat_heater_left"`
	SeatHeaterRight         int         `json:"seat_heater_right"`
	SeatHeaterRearLeft      int         `json:"seat_heater_rear_left"`
	SeatHeaterRearRight     int         `json:"seat_heater_rear_right"`
	SeatHeaterRearCenter    int         `json:"seat_heater_rear_center"`
	SeatHeaterRearRightBack int         `json:"seat_heater_rear_right_back"`
	SeatHeaterRearLeftBack  int         `json:"seat_heater_rear_left_back"`
	SmartPreconditioning    bool        `json:"smart_preconditioning"`
}

Contains the current climate states availale from the vehicle

type CommandResponse

type CommandResponse struct {
	Response struct {
		Reason string `json:"reason"`
		Result bool   `json:"result"`
	} `json:"response"`
}

Response from the Tesla API after POSTing a command

type DriveState

type DriveState struct {
	ShiftState interface{} `json:"shift_state"`
	Speed      float64     `json:"speed"`
	Latitude   float64     `json:"latitude"`
	Longitude  float64     `json:"longitude"`
	Heading    int         `json:"heading"`
	GpsAsOf    int64       `json:"gps_as_of"`
}

Contains the current drive state of the vehicle

type GuiSettings

type GuiSettings struct {
	GuiDistanceUnits    string `json:"gui_distance_units"`
	GuiTemperatureUnits string `json:"gui_temperature_units"`
	GuiChargeRateUnits  string `json:"gui_charge_rate_units"`
	Gui24HourTime       bool   `json:"gui_24_hour_time"`
	GuiRangeDisplay     string `json:"gui_range_display"`
}

Contains the current GUI settings of the vehicle

type Response

type Response struct {
	Bool bool `json:"response"`
}

The response when a state is requested

type SentryData

type SentryData struct {
	Mode string `json:"on"`
}

type StateRequest

type StateRequest struct {
	Response struct {
		*ChargeState
		*ClimateState
		*DriveState
		*GuiSettings
		*VehicleState
	} `json:"response"`
}

Represents the request to get the states of the vehicle

type StreamEvent

type StreamEvent struct {
	Timestamp  time.Time `json:"timestamp"`
	Speed      int       `json:"speed"`
	Odometer   float64   `json:"odometer"`
	Soc        int       `json:"soc"`
	Elevation  int       `json:"elevation"`
	EstHeading int       `json:"est_heading"`
	EstLat     float64   `json:"est_lat"`
	EstLng     float64   `json:"est_lng"`
	Power      int       `json:"power"`
	ShiftState string    `json:"shift_state"`
	Range      int       `json:"range"`
	EstRange   int       `json:"est_range"`
	Heading    int       `json:"heading"`
}

The event returned by the vehicle by the Tesla API

type Token

type Token struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
	Expires     int64
}

The token and related elements returned after a successful auth by the Tesla API

type Vehicle

type Vehicle struct {
	Color                  interface{} `json:"color"`
	DisplayName            string      `json:"display_name"`
	ID                     int64       `json:"id"`
	OptionCodes            string      `json:"option_codes"`
	VehicleID              int         `json:"vehicle_id"`
	Vin                    string      `json:"vin"`
	Tokens                 []string    `json:"tokens"`
	State                  string      `json:"state"`
	IDS                    string      `json:"id_s"`
	RemoteStartEnabled     bool        `json:"remote_start_enabled"`
	CalendarEnabled        bool        `json:"calendar_enabled"`
	NotificationsEnabled   bool        `json:"notifications_enabled"`
	BackseatToken          interface{} `json:"backseat_token"`
	BackseatTokenUpdatedAt interface{} `json:"backseat_token_updated_at"`
}

Represents the vehicle as returned from the Tesla API

func (Vehicle) AutoparkAbort

func (v Vehicle) AutoparkAbort() error

Causes the vehicle to abort the Autopark request

func (Vehicle) AutoparkForward

func (v Vehicle) AutoparkForward() error

Causes the vehicle to pull forward

func (Vehicle) AutoparkReverse

func (v Vehicle) AutoparkReverse() error

Causes the vehicle to go in reverse

func (*Vehicle) ChargeState

func (v *Vehicle) ChargeState() (*ChargeState, error)

ChargeState returns the charge state of the vehicle

func (Vehicle) ClimateState

func (v Vehicle) ClimateState() (*ClimateState, error)

ClimateState returns the climate state of the vehicle

func (Vehicle) Data

func (v Vehicle) Data(vid int64) (*StateRequest, error)

Data : Get data of the vehicle (calling this will not permit the car to sleep)

func (Vehicle) DriveState

func (v Vehicle) DriveState() (*DriveState, error)

func (*Vehicle) EnableSentry

func (v *Vehicle) EnableSentry() error

Enables Sentry Mode

func (Vehicle) FlashLights

func (v Vehicle) FlashLights() error

Flashes the lights of the vehicle

func (Vehicle) GuiSettings

func (v Vehicle) GuiSettings() (*GuiSettings, error)

GuiSettings returns the GUI settings of the vehicle

func (*Vehicle) HonkHorn

func (v *Vehicle) HonkHorn() error

Honks the horn of the vehicle

func (Vehicle) LockDoors

func (v Vehicle) LockDoors() error

Locks the doors of the vehicle

func (*Vehicle) MobileEnabled

func (v *Vehicle) MobileEnabled() (bool, error)

MobileEnabled returns if the vehicle is mobile enabled for Tesla API control

func (Vehicle) MovePanoRoof

func (v Vehicle) MovePanoRoof(state string, percent int) error

The desired state of the panoramic roof. The approximate percent open values for each state are open = 100%, close = 0%, comfort = 80%, vent = %15, move = set %

func (Vehicle) OpenChargePort

func (v Vehicle) OpenChargePort() error

Opens the charge port so you may insert your charging cable

func (Vehicle) OpenTrunk

func (v Vehicle) OpenTrunk(trunk string) error

Opens the trunk, where values may be 'front' or 'rear'

func (Vehicle) ResetValetPIN

func (v Vehicle) ResetValetPIN() error

Resets the PIN set for valet mode, if set

func (Vehicle) SetChargeLimit

func (v Vehicle) SetChargeLimit(percent int) error

Set the charge limit to a custom percentage

func (Vehicle) SetChargeLimitMax

func (v Vehicle) SetChargeLimitMax() error

Sets the charge limit to the max limit

func (Vehicle) SetChargeLimitStandard

func (v Vehicle) SetChargeLimitStandard() error

Sets the charge limit to the standard setting

func (Vehicle) SetTemprature

func (v Vehicle) SetTemprature(driver float64, passenger float64) error

Sets the temprature of the vehicle, where you may set the driver zone and the passenger zone to seperate temperatures

func (Vehicle) Start

func (v Vehicle) Start(password string) error

Start starts the car by turning it on, requires the password to be sent again

func (Vehicle) StartAirConditioning

func (v Vehicle) StartAirConditioning() error

StartAirConditioning starts the air conditioning in the car

func (Vehicle) StartCharging

func (v Vehicle) StartCharging() error

StartCharging starts the charging of the vehicle after you have inserted the charging cable

func (Vehicle) StopAirConditioning

func (v Vehicle) StopAirConditioning() error

Stops the air conditioning in the car

func (Vehicle) StopCharging

func (v Vehicle) StopCharging() error

Stop the charging of the vehicle

func (Vehicle) Stream

func (v Vehicle) Stream() (chan *StreamEvent, chan error, error)

Requests a stream from the vehicle and returns a Go channel

func (v Vehicle) TriggerHomelink() error

Opens and closes the configured Homelink garage door of the vehicle keep in mind this is a toggle and the garage door state is unknown a major limitation of Homelink

func (Vehicle) UnlockDoors

func (v Vehicle) UnlockDoors() error

Unlock the car's doors

func (Vehicle) VehicleState

func (v Vehicle) VehicleState() (*VehicleState, error)

func (Vehicle) Wakeup

func (v Vehicle) Wakeup() (*Vehicle, error)

Wakes up the vehicle when it is powered off

type VehicleResponse

type VehicleResponse struct {
	Response *Vehicle `json:"response"`
	Count    int      `json:"count"`
}

The response that contains the vehicle details from the Tesla API

type VehicleState

type VehicleState struct {
	APIVersion              int     `json:"api_version"`
	AutoParkState           string  `json:"autopark_state"`
	AutoParkStateV2         string  `json:"autopark_state_v2"`
	CalendarSupported       bool    `json:"calendar_supported"`
	CarType                 string  `json:"car_type"`
	CarVersion              string  `json:"car_version"`
	CenterDisplayState      int     `json:"center_display_state"`
	DarkRims                bool    `json:"dark_rims"`
	Df                      int     `json:"df"`
	Dr                      int     `json:"dr"`
	ExteriorColor           string  `json:"exterior_color"`
	Ft                      int     `json:"ft"`
	HasSpoiler              bool    `json:"has_spoiler"`
	Locked                  bool    `json:"locked"`
	NotificationsSupported  bool    `json:"notifications_supported"`
	Odometer                float64 `json:"odometer"`
	ParsedCalendarSupported bool    `json:"parsed_calendar_supported"`
	PerfConfig              string  `json:"perf_config"`
	Pf                      int     `json:"pf"`
	Pr                      int     `json:"pr"`
	RearSeatHeaters         int     `json:"rear_seat_heaters"`
	RemoteStart             bool    `json:"remote_start"`
	RemoteStartSupported    bool    `json:"remote_start_supported"`
	Rhd                     bool    `json:"rhd"`
	RoofColor               string  `json:"roof_color"`
	Rt                      int     `json:"rt"`
	SentryMode              bool    `json:"sentry_mode"`
	SentryModeAvailable     bool    `json:"sentry_mode_available"`
	SeatType                int     `json:"seat_type"`
	SpoilerType             string  `json:"spoiler_type"`
	SunRoofInstalled        int     `json:"sun_roof_installed"`
	SunRoofPercentOpen      int     `json:"sun_roof_percent_open"`
	SunRoofState            string  `json:"sun_roof_state"`
	ThirdRowSeats           string  `json:"third_row_seats"`
	ValetMode               bool    `json:"valet_mode"`
	VehicleName             string  `json:"vehicle_name"`
	WheelType               string  `json:"wheel_type"`
}

Contains the current state of the vehicle

type Vehicles

type Vehicles []struct {
	*Vehicle
}

Represents the vehicles from an account, as you could have more than one Tesla associated to your account

type VehiclesResponse

type VehiclesResponse struct {
	Response Vehicles `json:"response"`
	Count    int      `json:"count"`
}

The response that contains the vehicles details from the Tesla API

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL