-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtesla
1849 lines (1717 loc) · 47.4 KB
/
tesla
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# Talk to the Tesla servers to get car status
#
# API details:
# https://tesla-api.timdorr.com/
# https://www.teslaapi.io/vehicles/commands
#
AGENT="Preston Crow's Bash Tesla API 0.2"
TMPDIR=/tmp
DEBUGDIR=/tmp
TMP_FILE=${TMPDIR}/teslatmp.html
CONFIG_FILE=~/.teslarc
COOKIES=~/.cookies
# https://pastebin.com/pS7Z6yyP
_TESLA_CLIENT_ID=81527cff06843c8634fdc09e8ac0abefb46ac849f38fe1e431c2ef2106796384
_TESLA_CLIENT_SECRET=c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3
# ANSI color code defines
. ~/bin/bash_library
[ -f "${CONFIG_FILE}" ] && . "${CONFIG_FILE}"
#
# percent_encode()
#
# Encode the stream with percent hex codes for special characters
#
# If $1 is "limited" then don't encode '=' or '&'.
# If $1 is "url" then don't encode [:/?=&], but do [!$*()].
#
# In no case do we encode '%', so it is safe to pass through this multiple times.
#
percent_encode()
{
if [ "$1" == "limited" ]; then
sed -e 'sX"X%22Xg' -e 'sX/X%2FXg' -e 'sX}X%7DXg' -e 'sX{X%7BXg' -e 'sX;X%3BXg' -e 'sX,X%2CXg' -e 'sX?X%3FXg' -e 'sX<X%3CXg' -e 'sX>X%3EXg' -e 'sX X%20Xg' -e 'sX:X%3AXg' -e 'sX|X%7CXg'
elif [ "$1" == "url" ]; then
sed -e 'sX"X%22Xg' -e 'sX}X%7DXg' -e 'sX{X%7BXg' -e 'sX;X%3BXg' -e 'sX,X%2CXg' -e 'sX<X%3CXg' -e 'sX>X%3EXg' -e 'sX X%20Xg' -e 'sX|X%7CXg' -e 'sX[$]X%24Xg' -e 'sX[!]X%21Xg' -e 'sX[*]X%2AXg' -e 'sX(X%28Xg' -e 'sX)X%29Xg'
else
sed -e 'sX"X%22Xg' -e 'sX/X%2FXg' -e 'sX}X%7DXg' -e 'sX{X%7BXg' -e 'sX;X%3BXg' -e 'sX,X%2CXg' -e 'sX?X%3FXg' -e 'sX<X%3CXg' -e 'sX>X%3EXg' -e 'sX X%20Xg' -e 'sX:X%3AXg' -e 'sX=X%3DXg' -e 'sX&X%26Xg' -e 'sX|X%7CXg'
fi
}
#
# tesla_save_state()
#
tesla_save_state()
{
declare -p | grep '^declare [^ ]* TESLA_' > "${CONFIG_FILE}"
}
#
# post_clean()
#
# Clean up scriptified html
#
post_clean()
{
# tee ${DEBUGDIR}/debug.clean |
sed -e 'sX\\u003cX\x3cXg' -e 'sX\\u0025X\x25Xg' -e 'sX\\u0040X\x40Xg' -e 'sX\\u00b7X\xb7Xg' -e 'sX\\u00e9X\xe9Xg' -e 'sX\\nX\nXg' -e 'sX\\rXXg' -e 'sX\\tX\tXg' -e 'sX\\XXg' | strings
}
#
# load_page()
#
# $1 -- URL
# $2 -- file for results
# $3... -- extra headers
#
load_page()
{
local PARMS URL FILE
URL="$1"
shift
FILE="$1"
shift
unset http_proxy
PARMS=()
while [ -n "$1" ]; do
case "$1" in
-* )
PARMS+=( "$1")
;;
*)
PARMS+=( -H "$1" )
;;
esac
shift
done
# If using Cookies:
# local C="~/.cookies.txt"
# curl ... --cookie ${C} --cookie-jar ${C}
HTTP_CODE=$(timeout 3m curl --silent --location --compressed --cookie ${COOKIES} --cookie-jar ${COOKIES} --user-agent "${AGENT}" "${PARMS[@]}" "${URL}" --write-out "%{http_code}\n" --output "${FILE}")
return $?
}
#
# post_page()
#
# Load a page, and reload on failure
#
# Parameters:
# $1 -- URL to load
# $2 -- file for results
# $3 -- post data
# $4... -- extra headers
#
# Globals:
# AGENT
# HTTP_CODE
#
# Return:
# non-zero indicates failure
#
post_page()
{
local FAIL=0
local POST_DATA="$3"
local FILE="$2"
local URL="$1"
local PARMS
shift
shift
shift
PARMS=()
while [ -n "$1" ]; do
case "$1" in
-* )
PARMS+=( "$1")
;;
*)
PARMS+=( -H "$1" )
;;
esac
shift
done
HTTP_CODE=$(timeout 3m curl --request POST --silent --compressed --cookie ${COOKIES} --cookie-jar ${COOKIES} --user-agent "${AGENT}" --data-ascii "${POST_DATA}" "${PARMS[@]}" "${URL}" --output >( post_clean > "${FILE}" ) --write-out "%{http_code}\n")
if grep -q 'Error loading page' "${FILE}"; then
echo "$(date) ${FUNCNAME[0]}: ${ANSI_COLOR_RED}posting failed${ANSI_COLOR_DEFAULT}: ${URL}"
return 1
fi
return 0
}
#
# results_to_vars()
#
# pipe in the results of a standard JSON reques, and convert to
# global BASH variables
#
# $1 - variable prefix (optional)
#
results_to_vars()
{
local PREFIX="$1"
eval $(sed -e 's/^{//' -e 's/}$//' -e 's/,/\n/g' -e 's/":/=/g' | sed -e s/^\"/"${PREFIX}"/)
}
#
# tesla_token_valid()
#
# Return success if AUTH_access_token is defined and not expired
#
tesla_token_valid()
{
[ -z "${AUTH_access_token}" ] && return 1
[ -z "${AUTH_created_at}" ] && return 1
[ -z "${AUTH_expires_in}" ] && return 1
if [ $( date +%s ) -lt $(( AUTH_created_at + AUTH_expires_in )) ]; then
if [ $( date +%s -d "now + 24 hours" ) -gt $(( AUTH_created_at + AUTH_expires_in )) ]; then
false
### FIXME ### Renew the token
fi
return 0
fi
return 1
}
#
# tesla_login()
#
# $1 -- email address
# $2 -- password
#
# OLD OBSOLETE METHOD -- NO LONGER WORKS
#
tesla_login()
{
tesla_token_valid && return 0
local PW YN
if [ -z "${TESLA_email}" ]; then
echo -n "Enter Tesla account email address: "
read TESLA_email
fi
PW="${TESLA_password}"
if [ -z "${PW}" ]; then
echo -n "Enter Tesla account password: "
read PW
echo -n "Save password in "${CONFIG_FILE}"? (y/n) "
read YN
if [ "${YN::1}" == 'y' -o "${YN::1}" == 'Y' ]; then
TESLA_password="${PW}"
fi
fi
local POST_DATA="grant_type=password&client_id=${_TESLA_CLIENT_ID}&client_secret=${_TESLA_CLIENT_SECRET}&email=${TESLA_email}&password=${PW}"
local POST_URL="https://owner-api.teslamotors.com/oauth/token"
if ! post_page "${POST_URL}" "${TMP_FILE}" "${POST_DATA}"; then
return 1
fi
results_to_vars "AUTH_" < "${TMP_FILE}"
# echo token: ${AUTH_access_token}
tesla_save_state
return 0
}
#
# tesla_login()
#
# $1 -- email address
# $2 -- password
#
# Based on:
# https://tesla-api.timdorr.com/api-basics/authentication
#
tesla_login()
{
tesla_token_valid && return 0
local PW YN
if [ -z "${TESLA_email}" ]; then
echo -n "Enter Tesla account email address: "
read TESLA_email
fi
PW="${TESLA_password}"
if [ -z "${PW}" ]; then
echo -n "Enter Tesla account password: "
read PW
echo -n "Save password in "${CONFIG_FILE}"? (y/n) "
read YN
if [ "${YN::1}" == 'y' -o "${YN::1}" == 'Y' ]; then
TESLA_password="${PW}"
fi
fi
local URL POST_DATA STATUS CODE
#
# Step 1: Obtain the login page
#
TESLA_code_verifier=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 86)
TESLA_code_challenge=$(echo ${TESLA_code_verifier} | sha256sum | base64 --wrap=0)
TESLA_oath_state=$(tr -dc A-F0-9 </dev/urandom | head -c 32 ; echo '')
URL="client_id=ownerapi"
# URL+="?client_id=teslaweb" # works
URL+="&code_challenge=${TESLA_code_challenge}"
URL+="&code_challenge_method=S256"
URL+="&redirect_uri=https://auth.tesla.com/void/callback" # Works with 'ownerapi'
# URL+="&redirect_uri=https://www.tesla.com/openid-connect/generic" # Works with 'teslawab'
URL+="&response_type=code"
URL+="&scope=openid email offline_access"
URL+="&state=${TESLA_oath_state}"
URL="$(echo "${URL}" | percent_encode limited | sed -e 's/%20/+/g' )"
URL="https://auth.tesla.com/oauth2/v3/authorize?${URL}"
#echo "${URL}"
load_page "${URL}" ${TMP_FILE}
STATUS=$?
if [ ${STATUS} != 0 -o ${HTTP_CODE} != 200 ]; then
return 1
fi
#echo "load page: HTTP code ${HTTP_CODE}, status ${STATUS}"
#
# Step 2: Obtain an authorization code
#
POST_DATA="$(cat ${TMP_FILE} | sed -e '1,/<form/d' -e '/<.form/,$d' | grep input | grep hidden | sed -e 's/.*name="\([^"]*\)".*value="\([^"]*\)".*/\1=\2/' | tr '\n' '&')"
POST_DATA+="identity=${TESLA_email}&"
POST_DATA+="credential=${PW}"
#echo "POST data: ${POST_DATA}"
post_page "${URL}" "${TMP_FILE}" "${POST_DATA}"
STATUS=$?
CODE=$(cat ${TMP_FILE} | grep '[?&]code=' | sed -e 's/.*[&?]code=//' -e 's/&.*//')
if [ ${STATUS} != 0 -o ${HTTP_CODE} != 302 -o -z "${CODE}" ]; then
return 1
fi
#echo "post page: HTTP code ${HTTP_CODE}, status ${STATUS}, CODE ${CODE}"
#
# Step 3: Exchange authroization code for bearer token
#
POST_DATA='{"grant_type":"authorization_code","client_id":"ownerapi","code":"'${CODE}'","code_verifier":"'${TESLA_code_verifier}'","redirect_uri":"https://auth.tesla.com/void/callback"}'
post_page "https://auth.tesla.com/oauth2/v3/token" "${TMP_FILE}" "${POST_DATA}" "Content-Type:application/json" "Accept: application/json"
STATUS=$?
results_to_vars "AUTH_" < "${TMP_FILE}"
if [ ${STATUS} != 0 -o ${HTTP_CODE} != 200 -o -z "${AUTH_access_token}" ]; then
return 1
fi
#echo "post page: HTTP code ${HTTP_CODE}, status ${STATUS}, token ${AUTH_access_token}"
#
# Step 4: Exchange bearer token for access token
#
POST_DATA='{"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer","client_id": "'${_TESLA_CLIENT_ID}'","client_secret": "'${_TESLA_CLIENT_SECRET}'"}'
post_page "https://owner-api.teslamotors.com/oauth/token" "${TMP_FILE}" "${POST_DATA}" "Content-Type:application/json" "Accept: application/json" "Authorization: Bearer ${AUTH_access_token}"
STATUS=$?
results_to_vars "AUTH_" < "${TMP_FILE}"
if [ ${STATUS} != 0 -o ${HTTP_CODE} != 200 -o -z "${AUTH_access_token}" ]; then
return 1
fi
#echo "post page: HTTP code ${HTTP_CODE}, status ${STATUS}, token ${AUTH_access_token}"
tesla_save_state
return 0
}
#
# tesla_vehicle()
#
# Select the vehicle
#
# Creates variables of the form:
# Car_Name_ID with the ID to use for accessing the car
# TESLA_ids[]=( "..." "..." ... )
# TESLA_vehicles[]=( "car name 1" "car name 2" ... )
# TESLA_vins[]=( "5YJXXXXXXXX123456" "5YJXXXXXXXX123457" ... )
#
tesla_vehicle()
{
local URL="https://owner-api.teslamotors.com/api/1/vehicles"
false
load_page ${URL} ${TMP_FILE} "Authorization:Bearer ${AUTH_access_token}" || return 1
grep -q 'display_name' ${TMP_FILE} || return 1
TESLA_vins=()
TESLA_ids=()
TESLA_vehicles=()
eval $(cat ${TMP_FILE} | sed -e 's/"display_name":/\n&/g' | grep '^"display_name"' | sed -e 's/"display_name":"//' -e 's/",".*//' -e 's/.*:"//' -e 's/.*/TESLA_vehicles+=("&")/')
eval $(cat ${TMP_FILE} | sed -e 's/"vin":/\n&/g' | grep '^"vin"' | sed -e 's/"vin":"//' -e 's/",".*//' -e 's/.*:"//' -e 's/.*/TESLA_vins+=("&")/')
eval $(cat ${TMP_FILE} | sed -e 's/"id_s":/\n&/g' | grep '^"id_s"' | sed -e 's/"id_s":"//' -e 's/",".*//' -e 's/.*:"//' -e 's/.*/TESLA_ids+=("&")/')
eval $(cat ${TMP_FILE} | sed -e 's/"display_name":/\n&/g' | grep '^"display_name"' | sed -e 's/,.*,"id_s":"/_ID=/' -e 's/,.*//' -e 's/.*"//' -e 's/ /_/g' )
}
#
# tesla_location
#
# $AUTH_access_token
# $1 -- car index (0,1,...) (used if $2 is blank)
# $2 -- car ID (optional)
# $3 -- temporary file (use ${TMP_FILE} if blank)
#
tesla_location()
{
local INDEX="$1"
[ -z "${INDEX}" ] && INDEX=${TESLA_SELECTED_CAR}
local ID="$2"
[ -z "${ID}" ] && ID=${TESLA_ids[INDEX]}
local FILE="$3"
[ -z "${FILE}" ] && FILE="${TMP_FILE}"
unset TESLA_latitude TESLA_longitude
local URL="https://owner-api.teslamotors.com/api/1/vehicles/${ID}/data_request/drive_state"
load_page ${URL} ${FILE} "Authorization:Bearer ${AUTH_access_token}" || return 1
if grep -q 'vehicle unavailable' ${FILE}; then
# Vehicle is offline
return 0
fi
eval $(cat ${FILE} | sed -e 's/.*{//' -e 's/}.*/\n/' -e 's/,/\n/g' | sed -e 's/^"//' -e 's/":/=/' -e 's/^/TESLA_/')
}
#
# tesla_wake()
#
# Wake up the car
#
# $AUTH_access_token
# $1 -- car index (0,1,...) (used if $2 is blank)
# $2 -- car ID (optional)
# $3 -- temporary file (use ${TMP_FILE} if blank)
#
tesla_wake()
{
local ID="$2"
[ -z "${ID}" ] && ID=${TESLA_ids[$1]}
local FILE="$3"
[ -z "${FILE}" ] && FILE="${TMP_FILE}"
local URL="https://owner-api.teslamotors.com/api/1/vehicles/${ID}/wake_up"
#echo ''
#echo "Waking up... "
#echo "${URL}"
#echo "${FILE}"
post_page "${URL}" "${FILE}" "" "Authorization:Bearer ${AUTH_access_token}" || return 1
if [ ! -s "${FILE}" ]; then
echo "Empty post result file"
fi
grep -q "state" "${FILE}" && eval $(cat "${FILE}" | sed -e 's/.*{//' -e 's/}.*/\n/' -e 's/,/\n/g' | sed -e 's/^"//' -e 's/":/=/' -e 's/^/TESLA_/' | grep TESLA_state)
echo Result: ${TESLA_state}
echo HTTP status ${HTTP_CODE}
# FIXME: Should we wait for the car to wake up? Set a flag to keep polling?
}
#
# lat_long_addr()
#
# Get a street address from the lat/long
#
# Cache recent hits. If something matches to within +- 0.0001 lat or long, use the hit from the cache.
#
# Cache is two associative arrays with the same indices:
# TESLA_ADDRESS_CACHE[] -- text strings for the lat/long
# TESLA_ADDRESS_CACHE_TIME[] -- Unix time stamp of the last access time
#
# FIXME To-Do: There is currently no code to purge old entries, so the cache will grow indefinitely
#
# output:
# $LAT_LONG_ADDR
#
lat_long_addr()
{
declare -Ag TESLA_ADDRESS_CACHE
declare -Ag TESLA_ADDRESS_CACHE_TIME
local INDEX
# Create a cache index
INDEX="LL${TESLA_latitude%??}_${TESLA_longitude%??}"
INDEX="${INDEX//./p}"
INDEX="${INDEX//-/m}"
# Look up and return the address if cached
if [ -n "${TESLA_ADDRESS_CACHE[${INDEX}]}" ]; then
LAT_LONG_ADDR="${TESLA_ADDRESS_CACHE[${INDEX}]}"
TESLA_ADDRESS_CACHE_TIME[${INDEX}]=$(date +%s)
return
fi
# Get the address from openstreetmap.org
local URL="https://nominatim.openstreetmap.org/reverse?lat=${TESLA_latitude}&lon=${TESLA_longitude}"
load_page "${URL}" ${TMP_FILE} || return 1
LAT_LONG_ADDR="$(cat ${TMP_FILE} | grep addressparts | sed -e 'sX.*<addressparts>\(.*\)</addressparts>.*X\1X' -e 'sX<county>.*</county>XX' -e 'sX<country>.*</country>XX' -e 'sX<country_code>.*</country_code>XX' -e 'sX</house_number><road>X X' -e 'sX</state><postcode>X X' -e 'sX<[^>]*><[^>]*>X, Xg' -e 's/<[^>]*>//g')"
# Save the address in the cache
TESLA_ADDRESS_CACHE[${INDEX}]="${LAT_LONG_ADDR}"
TESLA_ADDRESS_CACHE_TIME[${INDEX}]=$(date +%s)
}
#
# rename_location()
#
# FIXME To-Do: Save the before and after such that the rename will impact all locations that resolve
# to the given address.
#
rename_location()
{
local INDEX ADDR
# Create a cache index
INDEX="LL${TESLA_latitude%??}_${TESLA_longitude%??}"
INDEX="${INDEX//./p}"
INDEX="${INDEX//-/m}"
restore_term
if [ -z "${TESLA_ADDRESS_CACHE[${INDEX}]}" ]; then
clear
echo ""
echo "Current address not found in the cache."
echo ""
sleep 5
return
fi
clear
echo ""
echo "Lat/Long: {TESLA_latitude},${TESLA_longitude}"
echo ""
echo "${TESLA_ADDRESS_CACHE[${INDEX}]}"
echo ""
echo "Enter new text to display for this location"
echo "(or enter to leave it alone)"
read ADDR
# Remove leading and trailing space
ADDR="${ADDR#"${ADDR%%[![:space:]]*}"}"
ADDR="${ADDR%"${ADDR##*[![:space:]]}"}"
# If no input; do nothing
[ -z "${ADDR}" ] && return
# Save new text
TESLA_ADDRESS_CACHE[${INDEX}]="${ADDR}"
}
#
# time_to_dest()
#
# Result:
# $SECS Seconds to reach home
# $STR String representing time and distance
#
time_to_dest()
{
local DEST="${1// /+}"
[ -z "${DEST}" ] && DEST="${TESLA_home_address}"
unset SECS
unset STR
[ -z "${TESLA_latitude}" ] && return 1
local URL A
if [ -z "${DEST}" ]; then
echo "Enter home address"
echo "Example: 123 Sesame St, New York, NY 12345"
echo -n "Address: "
read A
TESLA_home_address="${A// /+}"
DEST="${TESLA_home_address}"
fi
URL="https://www.google.com/maps/dir/${TESLA_latitude},${TESLA_longitude}/${DEST}/"
load_page "${URL}" ${TMP_FILE} || return 1
local DIST WAIT
eval $(cat ${TMP_FILE} | sed -e 's/[[]/\n&/g' -e 's/[]]/&\n/g' | grep '^[[]' | grep --after-context=1 '[0-9] miles' | sed -e 's/.*"\(.*\)\\".*/\1/' -e 's/[0-9] h/&our/' -e 's/.*/"&"/' | head -n 2 | sed -e 's/^/DIST=/' -e N -e 's/\n/ WAIT=/')
SECS=$(( $(date -d "now + ${WAIT}" +%s) - $(date +%s) ))
STR="${WAIT} away; ${DIST}"
return 0
}
#
# tesla_status_popup()
#
# Assumes TESLA_latitude, etc. are set.
# Assumes time_to_dest has been called.
#
# $1 -- message
# $2 -- background color
#
tesla_status_popup()
{
local STR2
# Get the address from openstreetmap.org
lat_long_addr
# Append gear/speed to status
case ${TESLA_shift_state} in
D ) STR2="; In DRIVE, ${TESLA_speed} mph" ;;
R ) STR2="; In REVERSE, ${TESLA_speed} mph" ;;
P ) STR2="; In PARK" ;;
null ) STR2="; Car is OFF" ;;
esac
# Pop up the notice
local W=${#LAT_LONG_ADDR}
[ ${#LAT_LONG_ADDR} -lt $(( ${#STR} + ${#STR2} )) ] && W=${#STR}
xterm -bg "$2" -fs 18 -geometry $((W+2))x5 -T "Tesla Alert" -e 'echo "";echo " '"$1"'";echo " '"${LAT_LONG_ADDR}"'";echo " '"${STR}${STR2}"'";read a'
}
#
# tesla_status_display()
#
# Assumes TESLA_latitude, etc. are set.
# Assumes time_to_dest has been called.
#
tesla_status_display()
{
echo ""
echo "${TESLA_vehicles[TESLA_SELECTED_CAR]}"
# Get the address from openstreetmap.org
if [ -n "${TESLA_latitude}" ]; then
lat_long_addr
# This version cleans up junk we don't care about and displays it more nicely
#cat ${TMP_FILE} | grep addressparts | sed -e 'sX.*<addressparts>\(.*\)</addressparts>.*X\1X' -e 'sX<county>.*</county>XX' -e 'sX<country>.*</country>XX' -e 'sX<country_code>.*</country_code>XX' -e 'sX</house_number><road>X X' -e 'sX</state><postcode>X X' -e 'sX<[^>]*><[^>]*>X, Xg' -e 's/<[^>]*>//g' -e 's/^/ /'
echo "${LAT_LONG_ADDR}"
if [ "${STR}" == " away; " ]; then
echo " almost home"
else
echo " ${STR}"
fi
fi
# Display gear/speed
if [ "${TESLA_power}" == 0 ]; then
echo " Car is ASLEEP"
else
case ${TESLA_shift_state} in
D ) echo " In DRIVE, ${TESLA_speed} mph" ;;
R ) echo " In REVERSE, ${TESLA_speed} mph" ;;
P ) echo " In PARK" ;;
null ) echo " Car is OFF" ;;
esac
fi
}
#
# drive_alert()
#
# Pop up an alert when the car is in DRIVE
#
drive_alert()
{
local DIS
tesla_login || return 1
tesla_vehicle || return 1
while true; do
tesla_location || return 1
if [ -z "${TESLA_latitude}" ]; then
sleep 15
continue
fi
if [ ${TESLA_shift_state} != D ]; then
sleep 15
continue
fi
time_to_dest
tesla_status_popup "Car is in DRIVE" "green"
break
done
return 0
}
#
# status_alert()
#
# Alert if the gear changes, car switches to/from off, goes to sleep or wakes up, or
# is within 5 mintues of home
#
status_alert()
{
local DIS GEAR AWAKE ON
local TARGET=$(( 5 * 60 ))
local W
[ -n "$1" ] && TARGET=$(( $1 * 60 ))
tesla_login || return 1
tesla_vehicle || return 1
while true; do
tesla_location || return 1
if [ -z "${TESLA_latitude}" ]; then
if [ "${AWAKE}" == yes ]; then
tesla_status_popup "Car is now asleep" "green"
fi
AWAKE=no
sleep 15
continue
fi
if [ "${TESLA_shift_state}" != "${GEAR}" ]; then
GEAR="${TESLA_shift_state}"
time_to_dest
if [ "${GEAR}" == "null" ]; then
tesla_status_popup "Car is off" "green"
else
tesla_status_popup "Car changed gears" "green"
fi
sleep 15
continue
fi
if [ "${TESLA_shift_state}" != "D" ]; then
sleep 15
continue
fi
time_to_dest
if [ ${SECS} -gt ${TARGET} ]; then
W=$(( ( SECS - TARGET ) / 2 ))
[ ${W} -lt 30 ] && W=30
sleep ${W}
continue
fi
tesla_status_popup 'ALMOST HOME!!!' "red"
break
done
return 0
}
#
# tesla_status()
#
tesla_status()
{
local DIS
tesla_login || return 1
tesla_vehicle || return 1
tesla_location || return 1
time_to_dest
tesla_status_popup "Car status" "green"
return 0
}
#
# tesla_monitor()
#
# Monitor the status of the car
#
tesla_monitor()
{
local THEN NOW ELAPSED STATE
tesla_login || return 1
tesla_vehicle || return 1
while true; do
tesla_location
if [ "${TESLA_power}" == 0 ]; then
LOC="Car is asleep"
STR=""
STATE=("$(date)")
else
time_to_dest
lat_long_addr
local LOC
LOC="${LAT_LONG_ADDR}"
# Append gear/speed to status
case ${TESLA_shift_state} in
D ) STATE="; In DRIVE, ${TESLA_speed} mph" ;;
R ) STATE="; In REVERSE, ${TESLA_speed} mph" ;;
P ) STATE="; In PARK" ;;
null ) STATE="; Car is OFF" ;;
esac
fi
clear
echo ""
echo " ${LOC}"
echo " ${STR}${STATE}"
THEN=$(date +%s)
while ! read -t 1 a; do
NOW=$(date +%s)
ELAPSED=$(( NOW - THEN ))
echo -n "[80D[K"
printf "%d:%02d" $(( ELAPSED/60 )) $(( ELAPSED % 60 ))
done
done
}
#
# tesla_gui_select_car()
#
tesla_gui_select_car()
{
if ! tesla_login; then
echo Failed to log in
return 1
fi
if ! tesla_vehicle; then
echo Failed to get list of vehicles
return 1
fi
tesla_save_state
if [ ${#TESLA_vehicles[@]} == 0 ]; then
echo No vehicles found
return 1
fi
if [ ${#TESLA_vehicles[@]} == 1 ]; then
TESLA_SELECTED_CAR="${TESLA_vehicles[0]}"
return 0
fi
#
# Multiple vehicles
#
# Print out a vehicle status summary, and then ask the user to click
# on the desired car.
#
unset TESLA_SELECTED_CAR
MAXLEN=${#TESLA_vehicles[0]}
for ((I=1;I<=${#TESLA_vehicles[@]};++I)); do
[ ${#TESLA_vehicles[I]} -gt ${MAXLEN} ] && MAXLEN=${#TESLA_vehicles[I]}
done
#
# Repeat this loop if we need to redraw the GUI due to window resizing
#
while true; do
clear
for ((I=0;I<LINES;++I)); do
echo ''
done
cat ${TMP_FILE} | sed -e 's/"display_name":/\n&/g' | grep '^"display_name"' | sed -e 's/^[^:]*://' -e 's/",".*,"state"//' -e 's/",".*//' -e 's/:"/: /' -e 's/"//'
echo ''
echo "Select a car"
echo ''
echo ''
echo ''
echo ''
button_init
button_add "Quit" "quit" 0 -1 -1
for ((I=0;I<${#TESLA_vehicles[@]};++I)); do
button_add "${TESLA_vehicles[I]}" $I 0 0
done
button_disp
button_get_click
if [ "${BUTTON_CLICKED}" == "quit" ]; then
restore_term
return 1
fi
if [ -n "${BUTTON_CLICKED}" ]; then
TESLA_SELECTED_CAR="${BUTTON_CLICKED}"
break
fi
done # draw GUI
tesla_save_state
return 0
}
#
# tesla_alert_dest_task()
#
# $1 -- car ID
# $2 -- temporary file
# $3 -- car Name
# $4 -- AUTH_access_token
# $5 -- time (default: 5 minutes)
# $6 -- Destination
#
tesla_alert_dest_task()
{
local ID="$1"
TMP_FILE="$2"
local NAME="$3"
AUTH_access_token="$4"
local TARGET="$5"
local DEST="$6"
while true; do
tesla_location "" "${ID}" || return 1
if [ -z "${TESLA_latitude}" ]; then
sleep 15
continue
fi
if [ ${TESLA_shift_state} == P ]; then
sleep 5
continue
fi
time_to_dest "${DEST}"
# echo "${NAME} time to home: $((SECS/60)):$((SECS/60/10))$((SECS/60%10))"
if [ ${SECS} -gt ${TARGET} ]; then
W=$(( ( SECS - TARGET ) / 2 ))
[ ${W} -lt 30 ] && W=30
sleep ${W}
continue
fi
if [ "${DEST}" == "${TESLA_home_address}" ]; then
tesla_status_popup "${NAME} is "'ALMOST HOME!!!' "red"
else
tesla_status_popup "${NAME} is "'ALMOST THERE!!!' "red"
fi
break
done
return 0
}
#
# tesla_alert_awake_task()
#
# $1 -- car ID
# $2 -- temporary file
# $3 -- car Name
# $4 -- AUTH_access_token
#
tesla_alert_awake_task()
{
local ID="$1"
TMP_FILE="$2"
local NAME="$3"
AUTH_access_token="$4"
while true; do
tesla_location "" "${ID}" || return 1
if [ -z "${TESLA_latitude}" ]; then
sleep 15
continue
fi
tesla_status_popup "${NAME} is AWAKE" "green"
break
done
return 0
}
#
# tesla_alert_gear_task()
#
# $1 -- car ID
# $2 -- temporary file
# $3 -- car Name
# $4 -- AUTH_access_token
#
tesla_alert_gear_task()
{
local ID="$1"
TMP_FILE="$2"
local NAME="$3"
AUTH_access_token="$4"
local GEAR
tesla_location "" "${ID}" || return 1
if [ -z "${TESLA_latitude}" ]; then
GEAR=ASLEEP
else
GEAR=${TESLA_shift_state}
fi
while true; do
tesla_location "" "${ID}" || return 1
if [ -z "${TESLA_latitude}" ]; then
if [ ${GEAR} != "ASLEEP" ]; then
tesla_status_popup "${NAME} is ASLEEP" "red"
break
fi
sleep 15
continue
fi
if [ ${TESLA_shift_state} == ${GEAR} ]; then
sleep 15
continue
fi
tesla_status_popup "${NAME} is now in gear ${TESLA_shift_state}" "green"
break
done
return 0
}
#
# tesla_alert_home()
#
# Alert when the car is within 5 minutes of home
#
tesla_alert_home()
{
local TARGET=$(( 5 * 60 ))
tesla_alert_dest_task "${TESLA_ids[TESLA_SELECTED_CAR]}" "${TMP_FILE}.${#ALERT_PIDS[*]}" "${TESLA_vehicles[TESLA_SELECTED_CAR]}" "${AUTH_access_token}" ${TARGET} "${TESLA_home_address}" &
ALERT_PIDS+=( $! )
ALERT_CAR+=( ${TESLA_SELECTED_CAR} )
ALERT_TARGET+=( time:${TARGET} )
ALERT_DEST+=( "${TESLA_home_address}" )
return 0
}
#
# tesla_alert_awake()
#
# Alert when the car is awake
#
tesla_alert_awake()
{
tesla_alert_awake_task "${TESLA_ids[TESLA_SELECTED_CAR]}" "${TMP_FILE}.${#ALERT_PIDS[*]}" "${TESLA_vehicles[TESLA_SELECTED_CAR]}" "${AUTH_access_token}" &
ALERT_PIDS+=( $! )
ALERT_CAR+=( ${TESLA_SELECTED_CAR} )
ALERT_TARGET+=( awake )
ALERT_DEST+=( "" )
return 0
}
#
# tesla_alert_dest()
#
# Alert when the car is within X minutes of [dest]
#
tesla_alert_dest()
{
tesla_alert_dest_task "${TESLA_ids[TESLA_SELECTED_CAR]}" "${TMP_FILE}.${#ALERT_PIDS[*]}" "${TESLA_vehicles[TESLA_SELECTED_CAR]}" "${AUTH_access_token}" $(( ${TESLA_dest_minutes[$1]} * 60 )) "${TESLA_dest_addr[$1]}" &
ALERT_PIDS+=( $! )
ALERT_CAR+=( ${TESLA_SELECTED_CAR} )
ALERT_TARGET+=( time:$(( ${TESLA_dest_minutes[$1]} * 60 )) )
ALERT_DEST+=( "${TESLA_dest_addr[$1]}" )
return 0
}
#
# tesla_alert_gear()
#
# Alert when the car changes gears
#
tesla_alert_gear()
{
tesla_alert_gear_task "${TESLA_ids[TESLA_SELECTED_CAR]}" "${TMP_FILE}.${#ALERT_PIDS[*]}" "${TESLA_vehicles[TESLA_SELECTED_CAR]}" "${AUTH_access_token}" &
ALERT_PIDS+=( $! )
ALERT_CAR+=( ${TESLA_SELECTED_CAR} )
ALERT_TARGET+=( gear )
ALERT_DEST+=( "" )
return 0
}
#
# tesla_alert_cancel()
#
# $1 -- index of alert to cancel (default: all)