forked from bmah888/gotesla
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gotesla.go
895 lines (775 loc) · 29.1 KB
/
gotesla.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//
// Copyright (C) 2019 Bruce A. Mah.
// All rights reserved.
//
// Distributed under a BSD-style license, see the LICENSE file for
// more information.
//
//
// 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.
//
package gotesla
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
)
// Tesla API parameters
// BaseURL is the leading part of the API URL. It is unlikely to ever change.
var BaseURL = "https://owner-api.teslamotors.com"
// 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.
var UserAgent = "org.kitchenlab.gotesla"
var teslaClientID = "e4a9949fcfa04068f59abb5a658f2bac0a3428e4652315490b659d5ab3f35a9e"
var teslaClientSecret = "c75f14bbadc8bee3a7594412c31416f8300256d7668ea7e6e7f06727bfb9d220"
// TokenCachePath is the location (UNIX specific?) to cache API credentials.
var TokenCachePath = os.Getenv("HOME") + "/.gotesla.cache"
// TokenCachePathNewSuffix is the suffix to add to a new cache file when updating.
var TokenCachePathNewSuffix = ".new"
//
// Authentication
//
// 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 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"`
}
// Token is basically an OAUTH 2.0 bearer token plus some metadata.
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"`
}
//
// GetToken authenticates with Tesla servers and returns a Token
// structure.
//
func GetToken(client *http.Client, username *string, password *string) (*Token, error) {
// Create JSON structure for authentication request
var auth Auth
auth.GrantType = "password"
auth.ClientID = teslaClientID
auth.ClientSecret = teslaClientSecret
auth.Email = *username
auth.Password = *password
// call common code
return tokenAuthCommon(client, &auth)
}
//
// RefreshToken refreshes an existing token and returns a new Token
// structure.
//
func RefreshToken(client *http.Client, token *Token) (*Token, error) {
// Create JSON structure for authentication request
var auth Auth
auth.GrantType = "refresh_token"
auth.ClientID = teslaClientID
auth.ClientSecret = teslaClientSecret
auth.RefreshToken = token.RefreshToken
// call common code
return tokenAuthCommon(client, &auth)
}
// Common authentication code used by GetToken and RefreshToken.
// Basically passes an authentication structure to Telsa and
// gets back a Token.
func tokenAuthCommon(client *http.Client, auth *Auth) (*Token, error) {
var verbose = false
var t Token
authjson, err := json.Marshal(auth)
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Auth JSON: %s\n", authjson)
}
body, err := PostTesla(client, nil, "/oauth/token", authjson)
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Resp JSON %s\n", body)
}
// Parse response, get token structure
err = json.Unmarshal(body, &t)
if err != nil {
return nil, err
}
return &t, nil
}
//
// 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 SaveCachedToken(t *Token) error {
// Convert the token structure to JSON
tokenJSON, err := json.Marshal(t)
if err != nil {
return err
}
// Write it to the file
err = ioutil.WriteFile(TokenCachePath+TokenCachePathNewSuffix, tokenJSON, 0600)
if err != nil {
return err
}
// Move into place
err = os.Rename(TokenCachePath+TokenCachePathNewSuffix, TokenCachePath)
if err != nil {
return err
}
return nil
}
// 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 GetAndCacheToken(client *http.Client, username *string, password *string) (*Token, error) {
t, err := GetToken(client, username, password)
if err != nil {
return t, err
}
err = SaveCachedToken(t)
if err != nil {
return t, err
}
return t, nil
}
// RefreshAndCacheToken does a refresh and saves the returned token in
// the local filesystem
// This function is preferred over RefreshToken.
func RefreshAndCacheToken(client *http.Client, token *Token) (*Token, error) {
t, err := RefreshToken(client, token)
if err != nil {
return t, err
}
err = SaveCachedToken(t)
if err != nil {
return t, err
}
return t, nil
}
// LoadCachedToken returns the token (if any) from the cache file.
func LoadCachedToken() (*Token, error) {
var t Token
body, err := ioutil.ReadFile(TokenCachePath)
if err != nil {
return nil, err
}
// Parse response, get token structure
err = json.Unmarshal(body, &t)
if err != nil {
return nil, err
}
return &t, nil
}
// DeleteCachedToken removes the cached token file.
func DeleteCachedToken() error {
err := os.Remove(TokenCachePath)
return err
}
// CheckToken returns true if a token is valid.
func CheckToken(t *Token) bool {
// Currently the only check is for timestamp validity, which
// assume the local clock is synchronized.
start, end := TokenTimes(t)
now := time.Now()
return (start.Before(now) && now.Before(end))
}
// TokenLifetime returns the remaining token lifetime
func TokenLifetime(t *Token) (lifetime time.Duration) {
_, end := TokenTimes(t)
lifetime = time.Until(end)
return
}
// TokenTimes returns the start and end times for a token.
func TokenTimes(t *Token) (start, end time.Time) {
start = time.Unix(int64(t.CreatedAt), 0)
end = time.Unix(int64(t.CreatedAt)+int64(t.ExpiresIn), 0)
return
}
//
// General Tesla API requests
//
// 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 GetTesla(client *http.Client, token *Token, endpoint string) ([]byte, error) {
var verbose = false
// Figure out the correct endpoint
var url = BaseURL + endpoint
if verbose {
fmt.Printf("URL: %s\n", url)
}
// Set up GET
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", UserAgent)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
if token != nil {
req.Header.Add("Authorization", "Bearer "+token.AccessToken)
}
if verbose {
fmt.Printf("Headers: %s\n", req.Header)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
// Try to handle certain types of HTTP status codes
if verbose {
fmt.Printf("Status: %s\n", resp.Status)
}
switch resp.StatusCode {
case http.StatusOK:
/* break */
default:
return nil, fmt.Errorf("%s", http.StatusText(resp.StatusCode))
}
// If we get here, we can be reasonably (?) assured of a valid body.
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Resp JSON %s\n", body)
}
// Caller needs to parse this in the context of whatever schema it knows
return body, nil
}
// PostTesla performs an HTTP POST request to the Tesla API.
func PostTesla(client *http.Client, token *Token, endpoint string, payload []byte) ([]byte, error) {
var verbose = false
// Compute endpoint URL
var url = BaseURL + endpoint
if verbose {
fmt.Printf("URL: %s\n", url)
}
// Set up POST
req, err := http.NewRequest("POST", url, bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", UserAgent)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
if token != nil {
req.Header.Add("Authorization", "Bearer "+token.AccessToken)
}
if verbose {
fmt.Printf("Headers: %s\n", req.Header)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Resp JSON %s\n", body)
}
// Caller needs to parse this in the context of whatever schema it knows
return body, nil
}
//
// Vehicle Information queries
//
// Vehicle is a structure that describes a single Tesla 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"`
}
// Vehicles encapsulates a collection of Tesla Vehicles.
type Vehicles []struct {
*Vehicle
}
// VehiclesResponse is the response to a vehicles API query.
type VehiclesResponse struct {
Response Vehicles `json:"response"`
Count int `json:"count"`
}
// GetVehicles performs a vehicles query to retrieve information on all
// the Tesla vehicles associated with an account.
func GetVehicles(client *http.Client, token *Token) (*Vehicles, error) {
var verbose = false
var vr VehiclesResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &vr)
if err != nil {
return nil, err
}
// Check Count to see if it matches the length of Response
if len(vr.Response) != vr.Count {
return nil, fmt.Errorf("get_vehicles Response length %d != Count %d", len(vr.Response), vr.Count)
}
return &(vr.Response), nil
}
// ChargeStateResponse is the return from a charge_state call
type ChargeStateResponse struct {
Response ChargeState
}
// ChargeState is the actual charge_state data
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"`
}
// GetChargeState retrieves the state of charge in the battery and various settings
func GetChargeState(client *http.Client, token *Token, ids string) (*ChargeState, error) {
var verbose = false
var csr ChargeStateResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/data_request/charge_state")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &csr)
if err != nil {
return nil, err
}
return &(csr.Response), nil
}
// ClimateStateResponse encapsulates a ClimateState object
type ClimateStateResponse struct {
Response ClimateState
}
// ClimateState returns the state of the climate control
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"`
}
// GetClimateState returns information on the current internal
// temperature and climate control system.
func GetClimateState(client *http.Client, token *Token, ids string) (*ClimateState, error) {
var verbose = false
var clsr ClimateStateResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/data_request/climate_state")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &clsr)
if err != nil {
return nil, err
}
return &(clsr.Response), nil
}
// DriveStateResponse encapsulates a DriveState object.
type DriveStateResponse struct {
Response DriveState
}
// DriveState is the result of the drive_state call, and includes information
// about vehicle position and speed
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
}
// GetDriveState returns the driving and position state of the vehicle
func GetDriveState(client *http.Client, token *Token, ids string) (*DriveState, error) {
var verbose = false
var dsr DriveStateResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/data_request/drive_state")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &dsr)
if err != nil {
return nil, err
}
return &(dsr.Response), nil
}
// GuiSettingsResponse encapsulates a GuiSettings object
type GuiSettingsResponse struct {
Response GuiSettings
}
// GuiSettings return a number of settings regarding the GUI on the CID
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
}
// GetGuiSettings returns various information about the GUI settings
// of the car, such as unit format and range display
func GetGuiSettings(client *http.Client, token *Token, ids string) (*GuiSettings, error) {
var verbose = false
var gsr GuiSettingsResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/data_request/gui_settings")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &gsr)
if err != nil {
return nil, err
}
return &(gsr.Response), nil
}
// VehicleStateResponse encapsulates a VehicleState object
type VehicleStateResponse struct {
Response VehicleState
}
// VehicleState is the return value from a vehicle_state call
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"`
}
// A VehicleStateMediaState returns the state of media control
type VehicleStateMediaState struct {
RemoteControlEnabled bool `json:"remote_control_enabled"`
}
// A VehicleStateSoftwareUpdate returns information on pending software updates
type VehicleStateSoftwareUpdate struct {
ExpectedDurationSec int `json:"expected_duration_sec"`
Status string `json:"status"`
}
// A VehicleStateSpeedLimitMode returns the speed limiting parameters
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"`
}
// GetVehicleState returns the vehicle's physical state, such as which
// doors are open.
func GetVehicleState(client *http.Client, token *Token, ids string) (*VehicleState, error) {
var verbose = false
var vsr VehicleStateResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/data_request/vehicle_state")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &vsr)
if err != nil {
return nil, err
}
return &(vsr.Response), nil
}
// VehicleConfigResponse encapsulates a VehicleConfig
type VehicleConfigResponse struct {
Response VehicleConfig
}
// VehicleConfig is the return data from a vehicle_config call
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"`
}
// GetVehicleConfig performs a vehicle_config call
func GetVehicleConfig(client *http.Client, token *Token, ids string) (*VehicleConfig, error) {
var verbose = false
var vcr VehicleConfigResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/data_request/vehicle_config")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &vcr)
if err != nil {
return nil, err
}
return &(vcr.Response), nil
}
// VehicleDataResponse is the return from a vehicle_data call
type VehicleDataResponse struct {
Response VehicleData
}
// VehicleData is the actual data structure for a vehicle_data call
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"`
}
// GetVehicleData performs a vehicle_data call
func GetVehicleData(client *http.Client, token *Token, ids string) (*VehicleData, error) {
var verbose = false
var vdr VehicleDataResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/vehicle_data")
if err != nil {
return nil, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &vdr)
if err != nil {
return nil, err
}
return &(vdr.Response), nil
}
// MobileEnabledResponse is the return from a mobile_enabled call
type MobileEnabledResponse struct {
Response bool `json:"response"`
}
// GetMobileEnabled returns whether mobile access is enabled
func GetMobileEnabled(client *http.Client, token *Token, ids string) (bool, error) {
var verbose = false
var mer MobileEnabledResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/mobile_enabled")
if err != nil {
return false, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &mer)
if err != nil {
return false, err
}
return mer.Response, nil
}
// Nearby Charging Sites
// ChargerLocation represents the physical coordinates of a charging station.
type ChargerLocation struct {
Lat float64 `json:"lat"`
Long float64 `json:"long"`
}
// Charger represents information common to all Tesla chargers.
type Charger struct {
Location ChargerLocation `json:"location"`
Name string `json:"name"`
Type string `json:"type"` // "destination" or "supercharger"
DistanceMiles float64 `json:"distance_miles"`
}
// DestinationCharger represents a Tesla Destination charger.
type DestinationCharger struct {
Charger
}
// Supercharger represents a Tesla Supercharger.
// In addition to the common Charger fields, this also includes
// information on stall occupancy.
type Supercharger struct {
Charger
AvailableStalls int `json:"available_stalls"`
TotalStalls int `json:"total_stalls"`
SiteClosed bool `json:"site_closed"`
}
// NearbyChargingSitesResponse encapsulates the response to a
// nearby_charging_sites API query on a given vehicle. Note that
// queries are specific to a given vehicle.
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"`
}
}
// GetNearbyChargers retrieves the chargers closest to a given vehicle.
func GetNearbyChargers(client *http.Client, token *Token, ids string) (NearbyChargingSitesResponse, error) {
var verbose = false
var ncsr NearbyChargingSitesResponse
vehiclejson, err := GetTesla(client, token, "/api/1/vehicles/"+ids+"/nearby_charging_sites")
if err != nil {
return ncsr, err
}
if verbose {
fmt.Printf("Response: %s\n", vehiclejson)
}
err = json.Unmarshal(vehiclejson, &ncsr)
if err != nil {
return ncsr, err
}
return ncsr, nil
}