gotesla

package module
v0.0.0-...-1f7781f Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2022 License: BSD-2-Clause Imports: 11 Imported by: 0

README

gotesla

Tesla API client library and utilities written in golang.

Tesla, Inc. has created an externally-accessible API for query and (to a very limited extent) controlling their vehicles, such as the Model S, Model X, and Model 3. This API is used by their mobile applications on iOS and Android. It is totally undocumented and unsupported by Tesla, however a number of third-party applications (desktop, mobile, Web sites) have been created that use this API.

This repository contains a limited implementation of a golang client library to access that API, along with a couple of utilities that exercise the client library and API. It was created solely for the author's personal use on a specific project (the aforementioned utilities), and is being made available in the hopes that it is useful to others. Please note that the author makes this code available on an "as-is" basis, and does not promise any support whatsoever.

Crowd-sourced, reverse-engineered information on the Tesla API has been obtained from (https://tesla-api.timdorr.com/), (https://github.com/vloschiavo/powerwall2/), and related sources. The author acknowledges and greatly appreciates the efforts of those who have contributed to this effort.

gettoken

A utility to obtain an authentication token from Tesla, used for various API calls. Requires a valid MyTesla account (email address) and password.

checktoken

Displays and manipulates the token in the local token cache.

scimport

Imports Supercharger stall utilization data to an InfluxDB timeseries database. The intended use case is to be able to visualize Supercharger stall use over time in a system such as Grafana.

pwimport

Imports Powerwall 2 power usage data (retrieved via direct access to a Powerwall gateway on the local network) into an InfluxDB timeseries database. Similar to scimport above.

pwsystat

Prints Powerwall 2 battery capacity information from the system_status API call, in human-readable form.

Copyright (C) 2019-2021 Bruce A. Mah. All rights reserved. Distributed under a BSD-style license, see the LICENSE file for more information.

Documentation

Overview

Package gotesla is a client library for Tesla vehicles

This package wraps some (but by no means all) of the various API calls and data structures in the Tesla API. Note that the API is not officially documented or supported; what is publically known has been reverse-engineered and collected at:

https://tesla-api.timdorr.com/

No attempt is made to document the functionality of the different API calls or data structures; for those details, please refer to the above Web site.

Index

Constants

This section is empty.

Variables

View Source
var BaseURL = "https://owner-api.teslamotors.com"

BaseURL is the leading part of the API URL. It is unlikely to ever change.

View Source
var TokenCachePath = os.Getenv("HOME") + "/.gotesla.cache"

TokenCachePath is the location (UNIX specific?) to cache API credentials.

View Source
var TokenCachePathNewSuffix = ".new"

TokenCachePathNewSuffix is the suffix to add to a new cache file when updating.

View Source
var UserAgent = "org.kitchenlab.gotesla"

UserAgent is passed in HTTP requests to the Tesla API. This appears to be a mandatory parameter; the API will not work without some value being passed here.

Functions

func CheckToken

func CheckToken(t *Token) bool

CheckToken returns true if a token is valid.

func DeleteCachedToken

func DeleteCachedToken() error

DeleteCachedToken removes the cached token file.

func GetMobileEnabled

func GetMobileEnabled(client *http.Client, token *Token, ids string) (bool, error)

GetMobileEnabled returns whether mobile access is enabled

func GetPowerwall

func GetPowerwall(client *http.Client, hostname string, endpoint string, pwa *PowerwallAuth) ([]byte, error)

GetPowerwall performs a GET request to a local Tesla Powerwall gateway. It doesn't do authentication yet.

func GetSoe

func GetSoe(client *http.Client, hostname string, pwa *PowerwallAuth) (float64, error)

GetSoe returns the state of energy of the Powerwall batteries. Unlike some other calls in this library, it doesn't return the structure, just a float64 value (and error if applicable).

func GetTesla

func GetTesla(client *http.Client, token *Token, endpoint string) ([]byte, error)

GetTesla performs a GET request to the Tesla API. If a non-nil authentication Token structure is passed, the bearer token part is used to authenticate the request.

func PostTesla

func PostTesla(client *http.Client, token *Token, endpoint string, payload []byte) ([]byte, error)

PostTesla performs an HTTP POST request to the Tesla API.

func SaveCachedToken

func SaveCachedToken(t *Token) error

SaveCachedToken saves a Token structure (JSON representation) in a file that is by default in the user's home directory. Writes the token to a temporary file and if that succeeds, move it atomically into place.

func TokenLifetime

func TokenLifetime(t *Token) (lifetime time.Duration)

TokenLifetime returns the remaining token lifetime

func TokenTimes

func TokenTimes(t *Token) (start, end time.Time)

TokenTimes returns the start and end times for a token.

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,omitempty"`
	Password     string `json:"password,omitempty"`
	RefreshToken string `json:"refresh_token,omitempty"`
}

Auth is an authorization structure for the Tesla API. Field names need to begin with capital letters for the JSON package to marshall them, but we use field tags to make the actual fields on the wire have the correct (all-lowercase) capitalization.

A user can either authenticate with an email and password, or if re-authenticating (refreshing a token), pass the refresh token.

type BatteryBlock

type BatteryBlock struct {
	PackagePartNumber      string
	PackageSerialNumber    string
	NominalFullPackEnergy  int `json:"nominal_full_pack_energy"`
	NominalEnergyRemaining int `json:"nominal_energy_remaining"`
	EnergyCharged          int `json:"energy_charged"`
	EnergyDischarged       int `json:"energy_discharged"`
}

type ChargeState

type 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"`
	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    bool        `json:"charge_port_cold_weather_mode"`
	ChargePortDoorOpen           bool        `json:"charge_port_door_open"`
	ChargePortLatch              string      `json:"charge_port_latch"` // "Engaged", "Disengaged"
	ChargeRate                   float64     `json:"charge_rate"`
	ChargeToMaxRange             bool        `json:"charge_to_max_range"`
	ChargerActualCurrent         int         `json:"charge_actual_current"`
	ChargerPhases                int         `json:"charge_phases"` // 1?
	ChargerPilotCurrent          int         `json:"charger_pilot_current"`
	ChargerPower                 int         `json:"charger_power"`
	ChargerVoltage               int         `json:"charger_voltage"`
	ChargingState                string      `json:"charging_state"` // "Stopped", "Starting", "Charging", "Disconnected"
	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     interface{} `json:"managed_charging_start_time"`
	ManagedChargingUserCancelled bool        `json:"managed_charging_user_cancelled"`
	MaxRangeChargeCounter        int         `json:"max_range_charge_counter"`
	NotEnoughPowerToHeat         bool        `json:"not_enough_power_to_heat"`
	ScheduledChargingPending     bool        `json:"scheduled_charging_pending"`
	ScheduledChargingStartTime   int         `json:"scheduled_charging_start_time"` // seconds
	TimeToFullCharge             float64     `json:"time_to_full_charge"`           // in hours
	TimeStamp                    int         `json:"timestamp"`                     // ms
	TripCharging                 bool        `json:"trip_charging"`
	UsableBatteryLevel           int         `json:"usable_battery_level"`
	UserChargeEnableRequest      bool        `json:"user_charge_enable_request"`
}

ChargeState is the actual charge_state data

func GetChargeState

func GetChargeState(client *http.Client, token *Token, ids string) (*ChargeState, error)

GetChargeState retrieves the state of charge in the battery and various settings

type ChargeStateResponse

type ChargeStateResponse struct {
	Response ChargeState
}

ChargeStateResponse is the return from a charge_state call

type Charger

type Charger struct {
	Location      ChargerLocation `json:"location"`
	Name          string          `json:"name"`
	Type          string          `json:"type"` // "destination" or "supercharger"
	DistanceMiles float64         `json:"distance_miles"`
}

Charger represents information common to all Tesla chargers.

type ChargerLocation

type ChargerLocation struct {
	Lat  float64 `json:"lat"`
	Long float64 `json:"long"`
}

ChargerLocation represents the physical coordinates of a charging station.

type ClimateState

type ClimateState struct {
	BatteryHeater              bool    `json:"battery_heater"`
	BatteryHeaterNoPower       bool    `json:"battery_heater_no_power"`
	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"`
	SeatHeaterRearCenter       int     `json:"seat_heater_rear_center"`
	SeatHeaterRearLeft         int     `json:"seat_heater_rear_left"`
	SeatHeaterRearLeftBack     int     `json:"seat_heater_rear_left_back"`
	SeatHeaterRearRight        int     `json:"seat_heater_rear_right"`
	SeatHeaterRearRightBack    int     `json:"seat_heater_rear_right_back"`
	SeatHeaterRight            int     `json:"seat_heater_right"`
	SideMirrorHeaters          bool    `json:"side_mirror_heaters"`
	SmartPreconditioning       bool    `json:"smart_preconditioning"`
	SteeringWheelHeater        bool    `json:"steering_wheel_heater"`
	TimeStamp                  int     `json:"timestamp"` // ms
	WiperBladeHeater           bool    `json:"wiper_blade_heater"`
}

ClimateState returns the state of the climate control

func GetClimateState

func GetClimateState(client *http.Client, token *Token, ids string) (*ClimateState, error)

GetClimateState returns information on the current internal temperature and climate control system.

type ClimateStateResponse

type ClimateStateResponse struct {
	Response ClimateState
}

ClimateStateResponse encapsulates a ClimateState object

type DestinationCharger

type DestinationCharger struct {
	Charger
}

DestinationCharger represents a Tesla Destination charger.

type DeviceCommon

type DeviceCommon struct {
	Din                   string
	PartNumber            string
	SerialNumber          string
	Manufacturer          string
	ComponentParentDin    string
	FirmwareVersion       string
	LastCommunicationTime int64
	EcuType               int32
	Alerts                []string
}

type DriveState

type 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              interface{} `json:"shift_state"`
	Speed                   interface{} `json:"speed"`
	TimeStamp               int         `json:"timestamp"` // ms
}

DriveState is the result of the drive_state call, and includes information about vehicle position and speed

func GetDriveState

func GetDriveState(client *http.Client, token *Token, ids string) (*DriveState, error)

GetDriveState returns the driving and position state of the vehicle

type DriveStateResponse

type DriveStateResponse struct {
	Response DriveState
}

DriveStateResponse encapsulates a DriveState object.

type GridStatus

type GridStatus int

GridStatus tracks the status of the grid connection to the house

const (
	GridStatusUnknown GridStatus = iota
	GridStatusDown
	GridStatusTransition
	GridStatusUp
)

GridStatus values

func GetGridStatus

func GetGridStatus(client *http.Client, hostname string, pwa *PowerwallAuth) (GridStatus, error)

GetGridStatus returns the grid status as a GridStatus value. We do it this way in order to avoid the caller needing to parse the response strings.

type GridStatusResponse

type GridStatusResponse struct {
	GridStatus string `json:"grid_status"`
}

GridStatusResponse is a structure that gives the current grid status as a string, as defined in the following constants.

type GuiSettings

type 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"`
	TimeStamp           int    `json:"timestamp"` // ms
}

GuiSettings return a number of settings regarding the GUI on the CID

func GetGuiSettings

func GetGuiSettings(client *http.Client, token *Token, ids string) (*GuiSettings, error)

GetGuiSettings returns various information about the GUI settings of the car, such as unit format and range display

type GuiSettingsResponse

type GuiSettingsResponse struct {
	Response GuiSettings
}

GuiSettingsResponse encapsulates a GuiSettings object

type Meter

type Meter struct {
	LastCommunicationTime string  `json:"last_communication_time"`
	InstantPower          float64 `json:"instant_power"`
	InstantReactivePower  float64 `json:"instant_reactive_power"`
	InstantApparentPower  float64 `json:"instant_apparent_power"`
	Frequency             float64 `json:"frequency"`
	EnergyExported        float64 `json:"energy_exported"`
	EnergyImported        float64 `json:"energy_imported"`
	InstantAverageVoltage float64 `json:"instant_average_voltage"`
	InstantTotalCurrent   float64 `json:"instant_total_current"`
	InstantACurrent       float64 `json:"instant_a_current"`
	InstantBCurrent       float64 `json:"instant_b_current"`
	InstantCCurrent       float64 `json:"instant_c_current"`
	Timeout               int     `json:"timeout"`
}

A Meter contains the state of one of the (four?) energy meters attached to the gateway.

type MeterAggregate

type MeterAggregate struct {
	Site      Meter
	Battery   Meter
	Load      Meter
	Solar     Meter
	Busway    Meter
	Frequency Meter
	Generator Meter
}

A MeterAggregate contains several Meters. Four of them correspond to the four energy sources in the Tesla app (Site, Battery, Load, and Solar). The remaining three are unknown at this time.

func GetMeterAggregate

func GetMeterAggregate(client *http.Client, hostname string, pwa *PowerwallAuth) (*MeterAggregate, error)

GetMeterAggregate retrieves a MeterAggregate from a local Powerwall gateway. No authentication is required for this call.

type MobileEnabledResponse

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

MobileEnabledResponse is the return from a mobile_enabled call

type NEURIO

type NEURIO struct {
	Common                 DeviceCommon
	MeterLocation          []uint32
	NEURIOCT0Location      string
	NEURIOCT0InstRealPower float64
}

type NearbyChargingSitesResponse

type NearbyChargingSitesResponse struct {
	Response struct {
		CongestionSyncTimeUtcSecs int                  `json:"congestion_sync_time_utc_secs"`
		DestinationCharging       []DestinationCharger `json:"destination_charging"`
		Superchargers             []Supercharger       `json:"superchargers"`
		Timestamp                 int                  `json:"timestamp"`
	}
}

NearbyChargingSitesResponse encapsulates the response to a nearby_charging_sites API query on a given vehicle. Note that queries are specific to a given vehicle.

func GetNearbyChargers

func GetNearbyChargers(client *http.Client, token *Token, ids string) (NearbyChargingSitesResponse, error)

GetNearbyChargers retrieves the chargers closest to a given vehicle.

type PVAC

type PVAC struct {
	Common                    DeviceCommon
	PVACIout                  float64
	PVACVL1Ground             float64
	PVACVL2Ground             float64
	PVACVHvMinusChassisDC     float64
	PVACPVCurrentA            float64
	PVACPVCurrentB            float64
	PVACPVCurrentC            float64
	PVACPVCurrentD            float64
	PVACPVMeasuredVoltageA    float64
	PVACPVMeasuredVoltageB    float64
	PVACPVMeasuredVoltageC    float64
	PVACPVMeasuredVoltageD    float64
	PVACPVMeasuredPowerA      float64
	PVACPVMeasuredPowerB      float64
	PVACPVMeasuredPowerC      float64
	PVACPVMeasuredPowerD      float64
	PVACLifetimeEnergyPVTotal float64
	PVACVout                  float64
	PVACFout                  float64
	PVACPout                  float64
	PVACQout                  float64
	PVACState                 string
	PVACGridState             string
	PVACInvState              string
	PVACPvStateA              string
	PVACPvStateB              string
	PVACPvStateC              string
	PVACPvStateD              string
	PVIPowerStatusSetpoint    string
}

type PVS

type PVS struct {
	Common              DeviceCommon
	PVSVLL              float64
	PVSState            string
	PVSSelfTestState    string
	PVSEnableOutput     bool
	PVSStringAConnected bool
	PVSStringBConnected bool
	PVSStringCConnected bool
	PVSStringDConnected bool
}

type PowerwallAuth

type PowerwallAuth struct {
	Email     string `json:"email"`
	Token     string `json:"token"`
	LoginTime string `json:"loginTime"`
	Timestamp time.Time
}

Authentication

func GetPowerwallAuth

func GetPowerwallAuth(client *http.Client, hostname string, email string, password string) (*PowerwallAuth, error)

GetPowerwallAuth gets a token (plus some other stuff) for authentication on a local Powerwall gateway

type STSTSM

type STSTSM struct {
	Common         DeviceCommon
	STSTSMLocation string
}

type SiteMasterResponse

type SiteMasterResponse struct {
	Running          bool   `json:"running"`
	Uptime           string `json:"uptime"`
	ConnectedToTesla bool   `json:"connected_to_tesla"`
}

SiteMasterResponse

func GetSiteMaster

func GetSiteMaster(client *http.Client, hostname string, pwa *PowerwallAuth) (*SiteMasterResponse, error)

type Soe

type Soe struct {
	Percentage float64 `json:"percentage"`
}

A Soe structure gives the current state of energy of the Powerwall batteries (total, as a value between 0-100).

type Supercharger

type Supercharger struct {
	Charger
	AvailableStalls int  `json:"available_stalls"`
	TotalStalls     int  `json:"total_stalls"`
	SiteClosed      bool `json:"site_closed"`
}

Supercharger represents a Tesla Supercharger. In addition to the common Charger fields, this also includes information on stall occupancy.

type SystemStatusResponse

type SystemStatusResponse struct {
	BatteryTargetPower     float64        `json:"battery_target_power"`
	NominalFullPackEnergy  int            `json:"nominal_full_pack_energy"`
	NominalEnergyRemaining int            `json:"nominal_energy_remaining"`
	AvailableBlocks        int            `json:"available_blocks"`
	BatteryBlocks          []BatteryBlock `json:"battery_blocks"`
	SystemIslandState      string         `json:"system_island_state"`
}

func GetSystemStatus

func GetSystemStatus(client *http.Client, hostname string, pwa *PowerwallAuth) (*SystemStatusResponse, error)

type TEMSA

type TEMSA struct {
	Common                        DeviceCommon
	ISLANDVL1NMain                float64
	ISLANDFreqL1Main              float64
	ISLANDVL1NLoad                float64
	ISLANDFreqL1Load              float64
	ISLANDPhaseL1MainLoad         float64
	ISLANDVL2NMain                float64
	ISLANDFreqL2Main              float64
	ISLANDVL2NLoad                float64
	ISLANDFreqL2Load              float64
	ISLANDPhaseL2MainLoad         float64
	ISLANDVL3NMain                float64
	ISLANDFreqL3Main              float64
	ISLANDVL3NLoad                float64
	ISLANDFreqL3Load              float64
	ISLANDPhaseL3MainLoad         float64
	ISLANDL1L2PhaseDelta          float64
	ISLANDL1L3PhaseDelta          float64
	ISLANDL2L3PhaseDelta          float64
	ISLANDGridState               string
	ISLANDL1MicrogridOk           bool
	ISLANDL2MicrogridOk           bool
	ISLANDL3MicrogridOk           bool
	ISLANDReadyForSynchronization bool
	ISLANDGridConnected           bool
	METERZCTAInstRealPower        float64
	METERZCTBInstRealPower        float64
	METERZCTAInstReactivePower    float64
	METERZCTBInstReactivePower    float64
	METERZLifetimeEnergyNetImport float64
	METERZLifetimeEnergyNetExport float64
	METERZVL1G                    float64
	METERZVL2G                    float64
	METERZCTAI                    float64
	METERZCTBI                    float64
}

type TEPINV

type TEPINV struct {
	Common                  DeviceCommon
	PINVEnergyDischarged    float64
	PINVEnergyCharged       float64
	PINVVSplit1             float64
	PINVVSplit2             float64
	PINVPllFrequency        float64
	PINVPllLocked           bool
	PINVPout                float64
	PINVQout                float64
	PINVVout                float64
	PINVFout                float64
	PINVReadyForGridForming bool
	PINVState               string
	PINVGridState           string
	PINVHardwareEnableLine  bool
	PINVPowerLimiter        string
}

type TEPOD

type TEPOD struct {
	Common                  DeviceCommon
	PODNomEnergyToBeCharged float64
	PODNomEnergyRemaining   float64
	PODNomFullPackEnergy    float64
	PODAvailableChargePower float64
	PODAvailableDischgPower float64
	PODState                string
	PODEnableLine           bool
	PODChargeComplete       bool
	PODDischargeComplete    bool
	PODPersistentlyFaulted  bool
	PODPermanentlyFaulted   bool
	PODChargeRequest        bool
	PODActiveHeating        bool
	PODCCVhold              bool
}

type TESLAMeter

type TESLAMeter struct {
	Common        DeviceCommon
	MeterLocation []uint32
}

type TESLAPV

type TESLAPV struct {
	Common              DeviceCommon
	NameplateRealPowerW uint64
}

type TESYNC

type TESYNC struct {
	Common                        DeviceCommon
	ISLANDVL1NMain                float64
	ISLANDFreqL1Main              float64
	ISLANDVL1NLoad                float64
	ISLANDFreqL1Load              float64
	ISLANDPhaseL1MainLoad         float64
	ISLANDVL2NMain                float64
	ISLANDFreqL2Main              float64
	ISLANDVL2NLoad                float64
	ISLANDFreqL2Load              float64
	ISLANDPhaseL2MainLoad         float64
	ISLANDVL3NMain                float64
	ISLANDFreqL3Main              float64
	ISLANDVL3NLoad                float64
	ISLANDFreqL3Load              float64
	ISLANDPhaseL3MainLoad         float64
	ISLANDL1L2PhaseDelta          float64
	ISLANDL1L3PhaseDelta          float64
	ISLANDL2L3PhaseDelta          float64
	ISLANDGridState               string
	ISLANDL1MicrogridOk           bool
	ISLANDL2MicrogridOk           bool
	ISLANDL3MicrogridOk           bool
	ISLANDReadyForSynchronization bool
	ISLANDGridConnected           bool
	SYNCExternallyPowered         bool
	SYNCSiteSwitchEnabled         bool
	METERXCTAInstRealPower        float64
	METERXCTBInstRealPower        float64
	METERXCTCInstRealPower        float64
	METERXCTAInstReactivePower    float64
	METERXCTBInstReactivePower    float64
	METERXCTCInstReactivePower    float64
	METERXLifetimeEnergyImport    float64
	METERXLifetimeEnergyExport    float64
	METERXVL1N                    float64
	METERXVL2N                    float64
	METERXVL3N                    float64
	METERXCTAI                    float64
	METERXCTBI                    float64
	METERXCTCI                    float64
	METERYCTAInstRealPower        float64
	METERYCTBInstRealPower        float64
	METERYCTCInstRealPower        float64
	METERYCTAInstReactivePower    float64
	METERYCTBInstReactivePower    float64
	METERYCTCInstReactivePower    float64
	METERYLifetimeEnergyImport    float64
	METERYLifetimeEnergyExport    float64
	METERYVL1N                    float64
	METERYVL2N                    float64
	METERYVL3N                    float64
	METERYCTAI                    float64
	METERYCTBI                    float64
	METERYCTCI                    float64
}

type TETHC

type TETHC struct {
	Common         DeviceCommon
	THCState       string
	THCAmbientTemp float64
}

type Token

type Token struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	CreatedAt    int    `json:"created_at"`
}

Token is basically an OAUTH 2.0 bearer token plus some metadata.

func GetAndCacheToken

func GetAndCacheToken(client *http.Client, username *string, password *string) (*Token, error)

GetAndCacheToken gets a new token and saves it in the local filesystem. This function is preferred over GetToken because it (in theory anyway) should result in fewer authentication calls to Tesla's servers due to caching.

func GetToken

func GetToken(client *http.Client, username *string, password *string) (*Token, error)

GetToken authenticates with Tesla servers and returns a Token structure.

func LoadCachedToken

func LoadCachedToken() (*Token, error)

LoadCachedToken returns the token (if any) from the cache file.

func RefreshAndCacheToken

func RefreshAndCacheToken(client *http.Client, token *Token) (*Token, error)

RefreshAndCacheToken does a refresh and saves the returned token in the local filesystem This function is preferred over RefreshToken.

func RefreshToken

func RefreshToken(client *http.Client, token *Token) (*Token, error)

RefreshToken refreshes an existing token and returns a new Token structure.

type Vehicle

type Vehicle struct {
	ID                     int         `json:"id"`
	VehicleID              int         `json:"vehicle_id"`
	Vin                    string      `json:"vin"`
	DisplayName            string      `json:"display_name"`
	OptionCodes            string      `json:"option_codes"`
	Color                  interface{} `json:"color"`
	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          interface{} `json:"backseat_token"`
	BackseatTokenUpdatedAt interface{} `json:"backseat_token_updated_at"`
}

Vehicle is a structure that describes a single Tesla vehicle.

type VehicleConfig

type VehicleConfig struct {
	CanAcceptNavigationRequests bool   `json:"can_accept_navigation_requests"`
	CanActuateTrunks            bool   `json:"can_actuate_trunks"`
	CarSpecialType              string `json:"car_special_type"` // "base"
	CarType                     string `json:"car_type"`         // "models"
	ChargePortType              string `json:"charge_port_type"`
	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"`
	PerfConfig                  string `json:"perf_config"`
	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"` // "Colored"
	SeatType                    int    `json:"seat_type"`
	SpoilerType                 string `json:"spoiler_type"`
	SunRoofInstalled            int    `json:"sun_roof_installed"`
	ThirdRowSeats               string `json:"third_row_seats"`
	TimeStamp                   int    `json:"timestamp"` // ms
	TrimBadging                 string `json:"trim_badging"`
	WheelType                   string `json:"wheel_type"`
}

VehicleConfig is the return data from a vehicle_config call

func GetVehicleConfig

func GetVehicleConfig(client *http.Client, token *Token, ids string) (*VehicleConfig, error)

GetVehicleConfig performs a vehicle_config call

type VehicleConfigResponse

type VehicleConfigResponse struct {
	Response VehicleConfig
}

VehicleConfigResponse encapsulates a VehicleConfig

type VehicleData

type VehicleData struct {
	Vehicle
	UserID int           `json:"user_id"`
	Ds     DriveState    `json:"drive_state"`
	Cls    ClimateState  `json:"climate_state"`
	Chs    ChargeState   `json:"charge_state"`
	Gs     GuiSettings   `json:"gui_settings"`
	Vs     VehicleState  `json:"vehicle_state"`
	Vc     VehicleConfig `json:"vehicle_config"`
}

VehicleData is the actual data structure for a vehicle_data call

func GetVehicleData

func GetVehicleData(client *http.Client, token *Token, ids string) (*VehicleData, error)

GetVehicleData performs a vehicle_data call

type VehicleDataResponse

type VehicleDataResponse struct {
	Response VehicleData
}

VehicleDataResponse is the return from a vehicle_data call

type VehicleState

type 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"`
	Ft                      int                        `json:"ft"`
	HomelinkNearby          bool                       `json:"homelink_nearby"`
	IsUserPresent           bool                       `json:"is_user_present"`
	LastAutoparkError       string                     `json:"last_autopark_error"`
	Locked                  bool                       `json:"locked"`
	MediaState              VehicleStateMediaState     `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"`
	RemoteStart             bool                       `json:"remote_start"`
	RemoteStartSupported    bool                       `json:"remote_start_started"`
	Rt                      int                        `json:"rt"`
	SoftwareUpdate          VehicleStateSoftwareUpdate `json:"software_update"`
	SpeedLimitMode          VehicleStateSpeedLimitMode `json:"speed_limit_mode"`
	SunRoofPercentOpen      int                        `json:"sun_roof_percent_open"`
	SunRoofState            string                     `json:"sun_roof_state"`
	TimeStamp               int                        `json:"timestamp"` // ms
	ValetMode               bool                       `json:"valet_mode"`
	ValetPinNeeded          bool                       `json:"valet_pin_needed"`
	VehicleName             string                     `json:"vehicle_name"`
}

VehicleState is the return value from a vehicle_state call

func GetVehicleState

func GetVehicleState(client *http.Client, token *Token, ids string) (*VehicleState, error)

GetVehicleState returns the vehicle's physical state, such as which doors are open.

type VehicleStateMediaState

type VehicleStateMediaState struct {
	RemoteControlEnabled bool `json:"remote_control_enabled"`
}

A VehicleStateMediaState returns the state of media control

type VehicleStateResponse

type VehicleStateResponse struct {
	Response VehicleState
}

VehicleStateResponse encapsulates a VehicleState object

type VehicleStateSoftwareUpdate

type VehicleStateSoftwareUpdate struct {
	ExpectedDurationSec int    `json:"expected_duration_sec"`
	Status              string `json:"status"`
}

A VehicleStateSoftwareUpdate returns information on pending software updates

type VehicleStateSpeedLimitMode

type VehicleStateSpeedLimitMode 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"`
}

A VehicleStateSpeedLimitMode returns the speed limiting parameters

type Vehicles

type Vehicles []struct {
	*Vehicle
}

Vehicles encapsulates a collection of Tesla Vehicles.

func GetVehicles

func GetVehicles(client *http.Client, token *Token) (*Vehicles, error)

GetVehicles performs a vehicles query to retrieve information on all the Tesla vehicles associated with an account.

type VehiclesResponse

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

VehiclesResponse is the response to a vehicles API query.

type VitalDevices

type VitalDevices struct {
	STSTSM      STSTSM
	TESYNC      TESYNC
	TEMSA       TEMSA
	TETHCs      []TETHC
	TEPODs      []TEPOD
	TEPINVs     []TEPINV
	PVACs       []PVAC
	PVSs        []PVS
	TESLAMeters []TESLAMeter
	NEURIOs     []NEURIO
	TESLAPVs    []TESLAPV
}

func GetVitals

func GetVitals(client *http.Client, hostname string, pwa *PowerwallAuth) (*VitalDevices, error)

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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