tesla

package module
v0.0.0-...-0b32acc Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2023 License: MIT Imports: 20 Imported by: 0

README

3/6/2021 - updated for new tesla authentication method

will require a python app for the initial token

Telsa class

This class is an example of how to use the unpublished tesla APIs to get information about a tesla and to change settings.

Needed documentation

The class uses the unpublished Tesla API to access a Telsa. Below are two different references. Both write-ups were needed to figure out how to communicate.

https://tesla-api.timdorr.com
https://www.teslaapi.io
https://pastebin.com/pS7Z6yyP

Secret values for the Authentication

Capabilities

Setup (house keeping)

These methods are used setup the authentication information into a database for future use with the Tesla API. The class has an sqlite3 database to store this information. It is recommend that you look at how to do a better job of securing this information. This is just an example.

Secrets

These are referenced in the authentication piece of the API. They are setup to be modified in the database in case they change. They never have changed since this project was started. The latest versions are here: https://pastebin.com/pS7Z6yyP

add secrets

Adds client id and client secret to database

get secrets

Gets the current values

updates secrets

Changes the current values

Usage recommendation

Use tesla_admin (see below) for all management of your database of credentials and vehicles. Then have your application using the tesla library do the rest of the work. You can do it differenntly - but the initial login to get the accesstoken has been changed by tesla. Instead, use the python script (in the python director) to get a json version of your initial accesstoken and ssorefreshtoken. Store that in a file and then use the "tesla_admin -cmd importtoken" command to import into your database.

Authentication

Provides authentication. Uses the user id and password of the tesla mobile app. Will receive a token that is used for auth going forward. The class has an sqlite3 database to store this information. It is recommend that you look at how to do a better job of securing this information. This is just an example.

login

Does not work anymore - Tesla changed their api. See: https://tesla-api.timdorr.com/api-basics/authentication#post-https-auth-tesla-com-oauth-2-v-3-token-1

for details. You will have to use the script in the python directory to create your initial accesstoken.

refreshtoken

Refreshes the token so user id/password prompting is not required. login above will auto call refreshtoken based on the time to live value in the token

wake

Wakes up the Telsa's computer for conversations with the rest of the APIs. From lots of testing, the wake command is important to have responded as successful. You can complete a login succesfully, but the car will not respond. Even if you have just completed talking to the car, it goes to sleep quickly :)

get owner

Provides details about the owner of the Tesla as stored in the database. Does not show password, but does show email and token information

delete owner

Removes all information from the database

Vehicle

All of the get/set commands require the unique vehicle ID. These methods provide two ways to get that information. See https://tesla-api.timdorr.com/api-basics/vehicles for details

Get Vehicle list

List of all vehicles registered to a single Telsa account - email address

Get Vehicle

Provides information about a specific vehicle based on the vehicle ID

Get Information

Provides a json of different types of information about the vehicle. See the API documentation links provided above for the details

Service data, Charge state, Drive state, GUI settings, Vehicle state, Vehicle config, Near By Charging

Set Information

Allows for the setting various items on the vehicle. At this point, the class only implemeted a call to setchargelimit. Others can be added as needed

Set Charge Limit

Sets the charging limit from 50-100% for the next charging cycle

Example code

tesla_cmd - Demo of how to use the tesla.go class

tesla login | getvehiclelist | addsecrets | getsecrets | getowner | delowner | refreshtoken | getvehiclelist | getchargestate | getclimatestate | updatesecrets 


Get State Cmds
nearbycharging vehicle_id : Gets vehicle state data
service_data vehicle_id : Gets service data
charge_state vehicle_id : Gts charge state data
climate_state vehicle_id : Gets climate state data
drive_state vehicle_id : Gets drive state data
gui_settings vehicle_id : Gets gui settings data
vehicle_config vehicle_id : Gets vehicle config data
vehicle_state vehicle_id : Gets vehicle state data

Set Cmds
wake vehicle_id - Wake up Vehicle
setchargelimit vehicle_id percent - Sets the charge limit

Utilities

tesla_admin - Admin command to setup the tesla.db for use with other utilities

  -clientid string
    	API Client ID (default "notset")
  -clientsec string
    	API Client Secret (default "notset")
  -cmd string
    	Command to run (default "help")
  -dbname string
    	Name of database (default "tesla.db")
  -rundir string
    	Directory to exec from (default "./")
  -vid string
    	VehicleId (default "notset")

cmds:
     Addsecrets - Add Tesla API secrets - needed for all APIs
     getsecrets - Displays Tesla API secrets - needed for all APIs
     updatesecrets - Updates Tesla API secrets - needed for all APIs
     login - Sets up login info
     refreshtoken - Refreshes token created via login
     ssorefreshtoken - Refreshes token created via login
     importtoken - Imports a json file from python script
     getowner - Shows owner details
     delowner - Deletes owner details
     setid - Stores vehicle ID for the cmds.  Requires -vid
     getid - Display vehicle ID for the cmds
     getvehiclelist - Displays a list of vehicles and their IDs owned by the login
     help - Display this help

tesla_chargelevel - Simple command to run from cron to reest the charging levels

  -cmd string
    	Command to run (default "help")
  -dbname string
    	Name of database (default "tesla.db")
  -highlimit string
    	charge high limit - used with homecharge (default "notset")
  -limit string
    	charge limit - used with setchargelimit (default "notset")
  -lowlimit string
    	charge low limit - used with homecharge (default "notset")
  -rundir string
    	Directory to exec from (default "./")

cmds:
     wake - Wake up vehicle
     setchargelimit - Set charge limit for next charge. Use -limit
     getchargelimit - Get charge limit for next charge
     batterylevel - Get current battery level
     homesetto50 - If vehicle is home, set to 50% charge limit
     homesetto80 - If vehicle is home, set to 80% charge limit
     homecharge - If vehicle is home, use -lowlimit and -highlimit level to adjust next charge limit
             -lowlimit - Level to set to so car does not charge every night
             -highlimit - Level to set to so car for next charge IF car is at low (or below) -lowlimit
             NOTE: If set to 100 already and car is below - will skip adjustments.  If charged, will set to low limit

Dependancies

Add these packages

go get github.com/mattn/go-sqlite3

go get github.com/seldonsmule/logmsg

go get github.com/seldonsmule/restapi

go get golang.org/x/crypto/ssh/terminal

go get github.com/denisbrodbeck/machineid

notes

Documentation

Index

Constants

View Source
const TESLA_API_URL = "https://owner-api.teslamotors.com"

Variables

This section is empty.

Functions

This section is empty.

Types

type MyDatabase

type MyDatabase struct {
	// contains filtered or unexported fields
}

func (*MyDatabase) AddApiDetails

func (edb *MyDatabase) AddApiDetails(clientId string, clientSecret string) bool

func (*MyDatabase) AddOwner

func (edb *MyDatabase) AddOwner(email string,
	accessToken string,
	refreshToken string,
	expiresTime int) bool

func (*MyDatabase) AddVehicleId

func (edb *MyDatabase) AddVehicleId(id string) bool

func (*MyDatabase) AddVehicleVin

func (edb *MyDatabase) AddVehicleVin(id string) bool

func (*MyDatabase) DelOwner

func (edb *MyDatabase) DelOwner() bool

func (*MyDatabase) DelVehicleId

func (edb *MyDatabase) DelVehicleId() bool

func (*MyDatabase) DelVehicleVin

func (edb *MyDatabase) DelVehicleVin() bool

func (*MyDatabase) GetApiDetails

func (edb *MyDatabase) GetApiDetails(pId *string, pSecret *string) bool

func (*MyDatabase) GetOwner

func (edb *MyDatabase) GetOwner(pEmail *string,
	pAccessToken *string,
	pRefreshToken *string,
	pExpiresTime *int) bool

func (*MyDatabase) GetVehicleId

func (edb *MyDatabase) GetVehicleId(pId *string) bool

func (*MyDatabase) GetVehicleVin

func (edb *MyDatabase) GetVehicleVin(pVin *string) bool

func (*MyDatabase) Hello

func (db *MyDatabase) Hello()
func (edb *MyDatabase) IsHomeLink() bool
func (edb *MyDatabase) SetHomeLink(state bool) bool

func (*MyDatabase) SetHomeLinkOff

func (edb *MyDatabase) SetHomeLinkOff() bool

func (*MyDatabase) SetHomeLinkOn

func (edb *MyDatabase) SetHomeLinkOn() bool

type MyLogin

type MyLogin struct {
}

func (*MyLogin) Prompt

func (et *MyLogin) Prompt(promptString string, reType bool) (resultString string, worked bool)

func (*MyLogin) TerminalLogin

func (et *MyLogin) TerminalLogin(userIDName string, authName string) (userid string, passwd string, worked bool)

type MyTesla

type MyTesla struct {
	SSO_state        string
	SSO_challenge    string
	SSO_challengeSum string

	//modelxoptions map[string]interface{}
	Modelxoptions map[string]string

	VehicleList     *restapi.Restapi
	SingleVehicle   *restapi.Restapi
	Wake            *restapi.Restapi
	Setchargelimit  *restapi.Restapi
	StopCharging    *restapi.Restapi
	NearbyCharging  *restapi.Restapi
	SSOrefreshtoken *restapi.Restapi

	DataRequestMap map[string]rest_cmds

	VehicleData TeslaVehicleData
	// contains filtered or unexported fields
}

func New

func New(dbName string) *MyTesla

func (*MyTesla) AddOwner

func (et *MyTesla) AddOwner()

func (*MyTesla) AddSecrets

func (et *MyTesla) AddSecrets()

func (*MyTesla) AddVehicleId

func (et *MyTesla) AddVehicleId(id string)

func (*MyTesla) AddVehicleVin

func (et *MyTesla) AddVehicleVin(vin string)

func (*MyTesla) DataRequest

func (et *MyTesla) DataRequest(id string, cmd string) bool

func (*MyTesla) DelOwner

func (et *MyTesla) DelOwner() bool

func (*MyTesla) DelVehicleId

func (et *MyTesla) DelVehicleId() bool

func (*MyTesla) DumpOwnerInfo

func (et *MyTesla) DumpOwnerInfo()

func (*MyTesla) ExpiresTimeStr

func (et *MyTesla) ExpiresTimeStr() string

func (*MyTesla) GetClientID

func (et *MyTesla) GetClientID() string

func (*MyTesla) GetClientSecret

func (et *MyTesla) GetClientSecret() string

func (*MyTesla) GetOwner

func (et *MyTesla) GetOwner() bool

func (*MyTesla) GetSecrets

func (et *MyTesla) GetSecrets() bool

func (*MyTesla) GetVehicleCmd

func (et *MyTesla) GetVehicleCmd(id string) bool

func (*MyTesla) GetVehicleData

func (et *MyTesla) GetVehicleData(id string) bool

func (*MyTesla) GetVehicleId

func (et *MyTesla) GetVehicleId() (bool, string)

func (*MyTesla) GetVehicleIdFromVinCmd

func (et *MyTesla) GetVehicleIdFromVinCmd(vin string) (bool, string)

func (*MyTesla) GetVehicleListCmd

func (et *MyTesla) GetVehicleListCmd() bool

func (*MyTesla) GetVehicleVin

func (et *MyTesla) GetVehicleVin() (bool, string)

func (*MyTesla) Help

func (et *MyTesla) Help()

func (*MyTesla) ImportTokens

func (et *MyTesla) ImportTokens() bool
func (et *MyTesla) IsHomeLink() bool

func (*MyTesla) Login

func (et *MyTesla) Login() bool

func (*MyTesla) ModelXOption

func (et *MyTesla) ModelXOption(code string) string

func (*MyTesla) NearbyChargingCmd

func (et *MyTesla) NearbyChargingCmd(id string) bool

func (*MyTesla) RefreshToken

func (et *MyTesla) RefreshToken(skipLogin bool) bool

func (*MyTesla) SSOLogin

func (et *MyTesla) SSOLogin() bool

func (*MyTesla) SSORefreshToken

func (et *MyTesla) SSORefreshToken() bool

func (*MyTesla) SSOauthorizeURL

func (et *MyTesla) SSOauthorizeURL() string

func (*MyTesla) SetChargeLimitCmd

func (et *MyTesla) SetChargeLimitCmd(id string, percent_value string) bool

func (*MyTesla) SetClientID

func (et *MyTesla) SetClientID(id string)

func (*MyTesla) SetClientSecret

func (et *MyTesla) SetClientSecret(secret string)

func (*MyTesla) SetHomeLinkOff

func (et *MyTesla) SetHomeLinkOff() bool

func (*MyTesla) SetHomeLinkOn

func (et *MyTesla) SetHomeLinkOn() bool

func (*MyTesla) StopChargingCmd

func (et *MyTesla) StopChargingCmd(id string) bool

func (*MyTesla) UpdateSecrets

func (et *MyTesla) UpdateSecrets() bool

func (*MyTesla) WakeCmd

func (et *MyTesla) WakeCmd(id string) bool

type TeslaVehicleData

type TeslaVehicleData struct {
	Response struct {
		ID                     int64    `json:"id"`
		UserID                 int      `json:"user_id"`
		VehicleID              int      `json:"vehicle_id"`
		Vin                    string   `json:"vin"`
		DisplayName            string   `json:"display_name"`
		Color                  any      `json:"color"`
		AccessType             string   `json:"access_type"`
		Tokens                 []string `json:"tokens"`
		State                  string   `json:"state"`
		InService              bool     `json:"in_service"`
		IDS                    string   `json:"id_s"`
		CalendarEnabled        bool     `json:"calendar_enabled"`
		APIVersion             int      `json:"api_version"`
		BackseatToken          any      `json:"backseat_token"`
		BackseatTokenUpdatedAt any      `json:"backseat_token_updated_at"`
		DriveState             struct {
			GpsAsOf                 int     `json:"gps_as_of"`
			Heading                 int     `json:"heading"`
			Latitude                float64 `json:"latitude"`
			Longitude               float64 `json:"longitude"`
			NativeLatitude          float64 `json:"native_latitude"`
			NativeLocationSupported int     `json:"native_location_supported"`
			NativeLongitude         float64 `json:"native_longitude"`
			NativeType              string  `json:"native_type"`
			Power                   int     `json:"power"`
			ShiftState              any     `json:"shift_state"`
			Speed                   any     `json:"speed"`
			Timestamp               int64   `json:"timestamp"`
		} `json:"drive_state"`
		ClimateState struct {
			BatteryHeater              bool    `json:"battery_heater"`
			BatteryHeaterNoPower       bool    `json:"battery_heater_no_power"`
			ClimateKeeperMode          string  `json:"climate_keeper_mode"`
			DefrostMode                int     `json:"defrost_mode"`
			DriverTempSetting          float64 `json:"driver_temp_setting"`
			FanStatus                  int     `json:"fan_status"`
			InsideTemp                 float64 `json:"inside_temp"`
			IsAutoConditioningOn       bool    `json:"is_auto_conditioning_on"`
			IsClimateOn                bool    `json:"is_climate_on"`
			IsFrontDefrosterOn         bool    `json:"is_front_defroster_on"`
			IsPreconditioning          bool    `json:"is_preconditioning"`
			IsRearDefrosterOn          bool    `json:"is_rear_defroster_on"`
			LeftTempDirection          int     `json:"left_temp_direction"`
			MaxAvailTemp               float64 `json:"max_avail_temp"`
			MinAvailTemp               float64 `json:"min_avail_temp"`
			OutsideTemp                float64 `json:"outside_temp"`
			PassengerTempSetting       float64 `json:"passenger_temp_setting"`
			RemoteHeaterControlEnabled bool    `json:"remote_heater_control_enabled"`
			RightTempDirection         int     `json:"right_temp_direction"`
			SeatHeaterLeft             int     `json:"seat_heater_left"`
			SeatHeaterRight            int     `json:"seat_heater_right"`
			SideMirrorHeaters          bool    `json:"side_mirror_heaters"`
			Timestamp                  int64   `json:"timestamp"`
			WiperBladeHeater           bool    `json:"wiper_blade_heater"`
		} `json:"climate_state"`
		ChargeState struct {
			BatteryHeaterOn             bool    `json:"battery_heater_on"`
			BatteryLevel                int     `json:"battery_level"`
			BatteryRange                float64 `json:"battery_range"`
			ChargeCurrentRequest        int     `json:"charge_current_request"`
			ChargeCurrentRequestMax     int     `json:"charge_current_request_max"`
			ChargeEnableRequest         bool    `json:"charge_enable_request"`
			ChargeEnergyAdded           float64 `json:"charge_energy_added"`
			ChargeLimitSoc              int     `json:"charge_limit_soc"`
			ChargeLimitSocMax           int     `json:"charge_limit_soc_max"`
			ChargeLimitSocMin           int     `json:"charge_limit_soc_min"`
			ChargeLimitSocStd           int     `json:"charge_limit_soc_std"`
			ChargeMilesAddedIdeal       float64 `json:"charge_miles_added_ideal"`
			ChargeMilesAddedRated       float64 `json:"charge_miles_added_rated"`
			ChargePortColdWeatherMode   any     `json:"charge_port_cold_weather_mode"`
			ChargePortDoorOpen          bool    `json:"charge_port_door_open"`
			ChargePortLatch             string  `json:"charge_port_latch"`
			ChargeRate                  float64 `json:"charge_rate"`
			ChargeToMaxRange            bool    `json:"charge_to_max_range"`
			ChargerActualCurrent        int     `json:"charger_actual_current"`
			ChargerPhases               int     `json:"charger_phases"`
			ChargerPilotCurrent         int     `json:"charger_pilot_current"`
			ChargerPower                int     `json:"charger_power"`
			ChargerVoltage              int     `json:"charger_voltage"`
			ChargingState               string  `json:"charging_state"`
			ConnChargeCable             string  `json:"conn_charge_cable"`
			EstBatteryRange             float64 `json:"est_battery_range"`
			FastChargerBrand            string  `json:"fast_charger_brand"`
			FastChargerPresent          bool    `json:"fast_charger_present"`
			FastChargerType             string  `json:"fast_charger_type"`
			IdealBatteryRange           float64 `json:"ideal_battery_range"`
			ManagedChargingActive       bool    `json:"managed_charging_active"`
			ManagedChargingStartTime    any     `json:"managed_charging_start_time"`
			ManagedChargingUserCanceled bool    `json:"managed_charging_user_canceled"`
			MaxRangeChargeCounter       int     `json:"max_range_charge_counter"`
			MinutesToFullCharge         int     `json:"minutes_to_full_charge"`
			NotEnoughPowerToHeat        bool    `json:"not_enough_power_to_heat"`
			ScheduledChargingPending    bool    `json:"scheduled_charging_pending"`
			ScheduledChargingStartTime  any     `json:"scheduled_charging_start_time"`
			TimeToFullCharge            float64 `json:"time_to_full_charge"`
			Timestamp                   int64   `json:"timestamp"`
			TripCharging                bool    `json:"trip_charging"`
			UsableBatteryLevel          int     `json:"usable_battery_level"`
			UserChargeEnableRequest     any     `json:"user_charge_enable_request"`
		} `json:"charge_state"`
		GuiSettings struct {
			Gui24HourTime       bool   `json:"gui_24_hour_time"`
			GuiChargeRateUnits  string `json:"gui_charge_rate_units"`
			GuiDistanceUnits    string `json:"gui_distance_units"`
			GuiRangeDisplay     string `json:"gui_range_display"`
			GuiTemperatureUnits string `json:"gui_temperature_units"`
			ShowRangeUnits      bool   `json:"show_range_units"`
			Timestamp           int64  `json:"timestamp"`
		} `json:"gui_settings"`
		VehicleState struct {
			APIVersion          int    `json:"api_version"`
			AutoparkStateV2     string `json:"autopark_state_v2"`
			AutoparkStyle       string `json:"autopark_style"`
			CalendarSupported   bool   `json:"calendar_supported"`
			CarVersion          string `json:"car_version"`
			CenterDisplayState  int    `json:"center_display_state"`
			Df                  int    `json:"df"`
			Dr                  int    `json:"dr"`
			FdWindow            int    `json:"fd_window"`
			FpWindow            int    `json:"fp_window"`
			Ft                  int    `json:"ft"`
			HomelinkDeviceCount int    `json:"homelink_device_count"`
			HomelinkNearby      bool   `json:"homelink_nearby"`
			IsUserPresent       bool   `json:"is_user_present"`
			LastAutoparkError   string `json:"last_autopark_error"`
			Locked              bool   `json:"locked"`
			MediaState          struct {
				RemoteControlEnabled bool `json:"remote_control_enabled"`
			} `json:"media_state"`
			NotificationsSupported  bool    `json:"notifications_supported"`
			Odometer                float64 `json:"odometer"`
			ParsedCalendarSupported bool    `json:"parsed_calendar_supported"`
			Pf                      int     `json:"pf"`
			Pr                      int     `json:"pr"`
			RdWindow                int     `json:"rd_window"`
			RemoteStart             bool    `json:"remote_start"`
			RemoteStartEnabled      bool    `json:"remote_start_enabled"`
			RemoteStartSupported    bool    `json:"remote_start_supported"`
			RpWindow                int     `json:"rp_window"`
			Rt                      int     `json:"rt"`
			SentryMode              bool    `json:"sentry_mode"`
			SentryModeAvailable     bool    `json:"sentry_mode_available"`
			SmartSummonAvailable    bool    `json:"smart_summon_available"`
			SoftwareUpdate          struct {
				DownloadPerc        int    `json:"download_perc"`
				ExpectedDurationSec int    `json:"expected_duration_sec"`
				InstallPerc         int    `json:"install_perc"`
				Status              string `json:"status"`
				Version             string `json:"version"`
			} `json:"software_update"`
			SpeedLimitMode struct {
				Active          bool    `json:"active"`
				CurrentLimitMph float64 `json:"current_limit_mph"`
				MaxLimitMph     int     `json:"max_limit_mph"`
				MinLimitMph     int     `json:"min_limit_mph"`
				PinCodeSet      bool    `json:"pin_code_set"`
			} `json:"speed_limit_mode"`
			SummonStandbyModeEnabled bool   `json:"summon_standby_mode_enabled"`
			SunRoofPercentOpen       int    `json:"sun_roof_percent_open"`
			SunRoofState             string `json:"sun_roof_state"`
			Timestamp                int64  `json:"timestamp"`
			ValetMode                bool   `json:"valet_mode"`
			ValetPinNeeded           bool   `json:"valet_pin_needed"`
			VehicleName              any    `json:"vehicle_name"`
		} `json:"vehicle_state"`
		VehicleConfig struct {
			CanAcceptNavigationRequests bool   `json:"can_accept_navigation_requests"`
			CanActuateTrunks            bool   `json:"can_actuate_trunks"`
			CarSpecialType              string `json:"car_special_type"`
			CarType                     string `json:"car_type"`
			ChargePortType              string `json:"charge_port_type"`
			DefaultChargeToMax          bool   `json:"default_charge_to_max"`
			EceRestrictions             bool   `json:"ece_restrictions"`
			EuVehicle                   bool   `json:"eu_vehicle"`
			ExteriorColor               string `json:"exterior_color"`
			HasAirSuspension            bool   `json:"has_air_suspension"`
			HasLudicrousMode            bool   `json:"has_ludicrous_mode"`
			MotorizedChargePort         bool   `json:"motorized_charge_port"`
			Plg                         bool   `json:"plg"`
			RearSeatHeaters             int    `json:"rear_seat_heaters"`
			RearSeatType                int    `json:"rear_seat_type"`
			Rhd                         bool   `json:"rhd"`
			RoofColor                   string `json:"roof_color"`
			SeatType                    int    `json:"seat_type"`
			SpoilerType                 string `json:"spoiler_type"`
			SunRoofInstalled            int    `json:"sun_roof_installed"`
			ThirdRowSeats               string `json:"third_row_seats"`
			Timestamp                   int64  `json:"timestamp"`
			TrimBadging                 string `json:"trim_badging"`
			UseRangeBadging             bool   `json:"use_range_badging"`
			WheelType                   string `json:"wheel_type"`
		} `json:"vehicle_config"`
	} `json:"response"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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