-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.js
executable file
·1004 lines (939 loc) · 46.4 KB
/
main.js
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
'use strict';
const utils = require('@iobroker/adapter-core');
const tjs = require('teslajs');
const tools = require(utils.controllerDir + '/lib/tools.js');
class TeslaMotors extends utils.Adapter {
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
constructor(options){
super({
...options,
name: 'tesla-motors',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.distanceUnit = '';
this.WakeItUpRetryCount = 30;
let dateNow = new Date();
this.lastTimeWokeUp = dateNow;
// Reset to 25 minutes ago to prevent from waking up the car every time the adapter restarts
this.lastTimeWokeUp.setMinutes(dateNow.getMinutes() - 26);
this.lastOverallRequest = new Date();
this.lastOverallRequest.setDate(dateNow.getDate() - 7);
this.lastWakeState = false;
// Timeouts and intervals
this.RefreshTokenTimeout = null;
this.RefreshRequestTimeout = null;
this.GetStandbyInfoTimeout = null;
this.RefreshAllInfoTimeout = null;
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady(){
this.log.debug('Starting Tesla Motors');
const Adapter = this;
await Adapter.setStateAsync('info.connection', false, true);
await this.setStateAsync('info.tokenExpire', (new Date(Adapter.config.tokenExpire)).toISOString(), true);
this.log.debug('All Objects installed, setting up tasks now');
this.subscribeStates('command.*');
// Setup Tasks
await Adapter.RefreshTokenTask();
await Adapter.RefreshStandbyInfoTask();
await Adapter.RefreshAllInfoTask();
}
onUnload(callback){
const Adapter = this;
try{
this.log.info('cleaned everything up...');
if(Adapter.RefreshTokenTimeout){
clearTimeout(Adapter.RefreshTokenTimeout);
}
if(Adapter.RefreshRequestTimeout){
clearTimeout(Adapter.RefreshRequestTimeout);
}
if(Adapter.GetStandbyInfoTimeout){
clearTimeout(Adapter.GetStandbyInfoTimeout);
}
if(Adapter.RefreshAllInfoTimeout){
clearTimeout(Adapter.RefreshAllInfoTimeout);
}
callback();
}catch(e){
callback();
}
}
async RefreshTokenTask(){
const Adapter = this;
Adapter.log.debug('Checking if token is valid');
await this.RefreshToken();
// Check again in 1 Day.
this.RefreshTokenTimeout = setTimeout(() => Adapter.RefreshTokenTask(), 60 * 60 * 1000);
}
async RefreshStandbyInfoTask(){
const Adapter = this;
// Only request if last overall request is also one minute ago
const seconds = Math.floor((new Date().getTime() - this.lastOverallRequest.getTime()) / 1000);
if(seconds > 59){
await Adapter.GetStandbyInfo();
}
// Check every minute the standby Info
this.GetStandbyInfoTimeout = setTimeout(() => Adapter.RefreshStandbyInfoTask(), 60 * 1000);
}
async RefreshAllInfoTask(){
const Adapter = this;
this.log.debug('Refresh of all in Task run. Current wakeupPlan is "' + Adapter.config.wakeupPlan + '"');
// Setting up Timeouts based on wakeup-Plan
switch(Adapter.config.wakeupPlan){
case 'aggressive':
await Adapter.GetAllInfo();
Adapter.RefreshAllInfoTimeout = setTimeout(() => Adapter.RefreshAllInfoTask(), 1000); // once per second
break;
case 'temperate':
await Adapter.GetAllInfo();
Adapter.RefreshAllInfoTimeout = setTimeout(() => Adapter.RefreshAllInfoTask(), 60 * 60 * 1000); // once per hour
break;
case 'off':
// Only get data when something changes or car is awake anyway (Done in GetSleepingInfo)
break;
case 'smart':
default:
/* Theory:
* When car wakes up, there is something happening.
* So if car woke up, get data every minute for 10 minutes.
* If nothing happened (Car start, Climate start, Charging) leave car alone to let him fall asleep.
* If not went to sleep, request data and wait again 15 minutes.
* But: If last wake up is more than 12 hours ago, request state!
*
*/
let NextRefresh = 5;
let Minutes = Math.floor((new Date().getTime() - this.lastTimeWokeUp.getTime()) / 60000);
// if car is in use, set lastTimeWokeUp to 0
let shift_state = await Adapter.getStateAsync('driveState.shift_state');
let speed = await Adapter.getStateAsync('driveState.speed');
let climate = await Adapter.getStateAsync('command.Climate');
let chargeState = await Adapter.getStateAsync('chargeState.charging_state');
let inUse = '';
if(shift_state && shift_state.val !== null && shift_state.val !== "P") inUse = 'Shift State = ' + shift_state.val;
else if(speed && speed.val > 0) inUse = 'Speed ' + speed.val;
else if(climate && climate.val) inUse = 'Climate';
else if(chargeState
&& chargeState.val !== 'Disconnected'
&& chargeState.val !== 'Complete'
&& chargeState.val !== 'NoPower'
&& chargeState.val !== 'Stopped') inUse = 'Charging state = ' + chargeState.val;
if(inUse.length > 0){
this.lastTimeWokeUp = new Date();
Minutes = 0;
Adapter.log.debug("Reset last wake up time because car seems to be in use (Reason: " + inUse + ").");
}
if((shift_state && shift_state.val !== null && shift_state.val !== "P") ||
(speed && speed.val > 0)){
NextRefresh = 1;
}
if(Minutes <= 10){
Adapter.log.debug("Get all info because last time it woke up is only " + Minutes + " Minutes ago.");
NextRefresh = 10;
await Adapter.GetAllInfo();
}
else if(Minutes > 10 && Minutes <= 25){
// Don't do anything, try to let the car sleep...
NextRefresh = 30;
Adapter.log.debug("Don't wake up the car and let it go to sleep. Minutes since last woke up: " + Minutes);
}
else if(Minutes > 25){
// Check if car is still awake. If so, request once and then go back to "let it sleep"
let standby = await Adapter.getStateAsync('command.standby');
if(standby && !standby.val && standby.ack){
Adapter.log.debug("Car is still awake after 25 Minutes. Retry to let him fall asleep for 15 minutes");
await Adapter.GetAllInfo();
this.lastTimeWokeUp = new Date();
this.lastTimeWokeUp.setMinutes(new Date().getMinutes() - 11);
}
else{
Adapter.log.debug("Car fall asleep successfully, will leave him alone for a while...");
NextRefresh = 10;
}
}
Adapter.RefreshAllInfoTimeout = setTimeout(() => Adapter.RefreshAllInfoTask(), NextRefresh * 1000); // check every Second
break;
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state){
const Adapter = this;
if(!state) return;
Adapter.log.debug("State Change: " + id + " to " + state.val + " ack " + state.ack);
const State = await Adapter.getStateAsync('info.connection');
if(!State || !State.val){
Adapter.log.warn('You tried to set a State, but there is currently no valid Token, please configure Adapter first!');
return;
}
let options = {
authToken: Adapter.config.authToken,
vehicleID: Adapter.config.vehicle_id_s
};
const currentId = id.substring(Adapter.namespace.length + 1);
if(state && !state.ack){
let requestDataChange = true;
const awake = await Adapter.WakeItUp();
if(!awake) return;
switch(currentId){
case 'command.standby':
if(state.val){
await tjs.wakeUpAsync(options);
}
break;
case 'command.doorLock':
if(state.val){
await tjs.doorLockAsync(options);
}
else{
await tjs.doorUnlockAsync(options);
}
break;
case 'command.homelink':
const latitude = await Adapter.getStateAsync('driveState.latitude');
const longitude = await Adapter.getStateAsync('driveState.longitude');
const devices = await Adapter.getStateAsync('vehicle.homelink_device_count');
const nearby = await Adapter.getStateAsync('vehicle.homelink_nearby');
if(!latitude || !longitude || !devices || !nearby){
Adapter.log.warn('Not all states exists for homelink');
break;
}
Adapter.log.debug("Homelink devices: " + devices.val + " Nearby: " + nearby.val == true ? 'Yes' : 'No');
const res = await tjs.homelinkAsync(options, latitude.val, longitude.val);
if(res.result){
Adapter.log.debug("Homelink: " + "Door signaled!");
}
else{
Adapter.log.warn("Homelink: " + res.result);
}
break;
case 'command.honkHorn':
if(state.val){
await tjs.honkHornAsync(options);
Adapter.setState('command.honkHorn', false, true);
}
break;
case 'command.flashLight':
if(state.val){
await tjs.flashLightsAsync(options);
Adapter.setState('command.flashLight', false, true);
}
break;
case 'command.Climate':
if(state.val){
await tjs.climateStartAsync(options);
}
else{
await tjs.climateStopAsync(options);
}
break;
case 'command.SetTemperature':
let minTemp = await Adapter.getStateAsync('climateState.min_avail_temp');
let maxTemp = await Adapter.getStateAsync('climateState.max_avail_temp');
if(!minTemp || !maxTemp){
Adapter.log.warn('Min and Max temp do not exists!');
}
else{
if(state.val > maxTemp.val) state.val = maxTemp.val;
if(state.val < minTemp.val) state.val = minTemp.val;
}
await tjs.setTempsAsync(options, state.val, state.val);
break;
case 'command.SetChargeLimit':
if(parseInt(state.val) > 100 || parseInt(state.val) < 0){
Adapter.setState('command.SetChargeLimit', 80, true);
}
else await tjs.setChargeLimitAsync(options, state.val);
break;
case 'command.ChargePort':
if(state.val){
await tjs.openChargePortAsync(options);
}
else{
await tjs.closeChargePortAsync(options);
}
break;
case 'command.UnlockChargePort':
const ChargePort = await Adapter.getStateAsync('command.ChargePort');
if(ChargePort){
await tjs.openChargePortAsync(options);
}
Adapter.setState('command.UnlockChargePort', false, true);
break;
case 'command.Charging':
if(state.val){
let charge = await tjs.startChargeAsync(options).catch((err) => {
Adapter.log.error('Err:' + err);
});
if(charge.result === false){
Adapter.setState('command.Charging', false, true);
}
else{
Adapter.setState('command.Charging', true, true);
}
}
else{
await tjs.stopChargeAsync(options);
Adapter.setState('command.Charging', false, true);
}
break;
case 'command.ValetMode':
const ValetPin = await Adapter.getStateAsync('command.ValetPin');
if(!ValetPin){
break;
}
if(/^\d{4}$/.test(ValetPin.val)){
await tjs.setValetModeAsync(options, state.val, ValetPin.val);
}
else{
if(!state.val){ // Ensure valet mode is off anyway!
await tjs.setValetModeAsync(options, false, '0000');
await tjs.resetValetPinAsync(options);
}
Adapter.setState('command.ValetPin', '????');
}
break;
case 'command.SpeedLimit':
if(state.val){
await tjs.speedLimitActivateAsync(options);
}
else{
await tjs.speedLimitDeactivateAsync(options);
}
break;
case 'command.SpeedLimitValue':
let min = await Adapter.getStateAsync('driveState.SpeedLimitMin');
let max = await Adapter.getStateAsync('driveState.SpeedLimitMax');
if(!min || !max){
Adapter.log.warn('Min and Max Speed do not exists!');
}
else{
if(state.val > max.val) state.val = max.val;
if(state.val < min.val) state.val = min.val;
}
await tjs.speedLimitSetLimitAsync(options, Adapter.km_m(state.val));
break;
case 'command.SentryMode':
await tjs.setSentryModeAsync(options, state.val);
break;
case 'command.RemoteStart':
await tjs.remoteStartAsync(options, state.val);
break;
case 'command.SunRoofVent':
await tjs.sunRoofControlAsync(options, state.val ? "vent" : "close");
break;
case 'command.StartSoftwareUpdate':
await tjs.scheduleSoftwareUpdateAsync(options, 0);
break;
case 'command.seat_heater_left':
if(state.val < 0) state.val = 0;
if(state.val > 3) state.val = 3;
await tjs.seatHeaterAsync(options, 0, state.val);
break;
case 'command.seat_heater_right':
if(state.val < 0) state.val = 0;
if(state.val > 3) state.val = 3;
await tjs.seatHeaterAsync(options, 1, state.val);
break;
case 'command.seat_heater_rear_center':
if(state.val < 0) state.val = 0;
if(state.val > 3) state.val = 3;
await tjs.seatHeaterAsync(options, 4, state.val);
break;
case 'command.seat_heater_rear_left':
if(state.val < 0) state.val = 0;
if(state.val > 3) state.val = 3;
await tjs.seatHeaterAsync(options, 2, state.val);
break;
case 'command.seat_heater_rear_right':
if(state.val < 0) state.val = 0;
if(state.val > 3) state.val = 3;
await tjs.seatHeaterAsync(options, 5, state.val);
break;
case 'command.steering_wheel_heater':
await tjs.steeringHeaterAsync(options, state.val ? 3 : 0);
break;
case 'command.windowVent':
await tjs.windowControlAsync(options, state.val ? 'vent' : 'close');
break;
case 'command.openTrunk':
await tjs.openTrunkAsync(options, tjs.TRUNK);
Adapter.setState('command.openTrunk', false, true);
break;
case 'command.openFrunk':
await tjs.openTrunkAsync(options, tjs.FRUNK);
Adapter.setState('command.openFrunk', false, true);
break;
default:
requestDataChange = false;
break;
}
if(requestDataChange){ // After a manual request, always reset sleep timer, but only to 2 minutes
this.lastTimeWokeUp.setMinutes(new Date().getMinutes() - 8);
}
this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
}
}
async onMessage(msg){
const Adapter = this;
Adapter.log.debug('Got a Message: ' + msg.command);
if(msg.command === 'getToken'){
// Get a Token
let username = msg.message.teslaUsername;
let password = tools.decrypt('rEYbFGzsXW8QBx5', msg.message.teslaPassword);
let mfaPassCode = tools.decrypt('rEYbFGzsXW8QBx5', msg.message.teslaMfaPassCode);
if(username.length == 0 || password.length == 0){
Adapter.log.error("Your authentification token is not valid or expired. Can't get a new token because you did not store username / password. Please request a new token in Adapter Configuration");
Adapter.sendTo(msg.from, msg.command, {success: false}, msg.callback);
return;
}
Adapter.log.info('Try to get a token');
let Response = await new Promise(async resolve => {
tjs.login({
username: username,
password: password,
mfaPassCode: mfaPassCode
}
, async (err, result) => {
if(result.error || !result.authToken){
let errMsg = 'No response';
if(result.body != undefined && result.body.response != undefined){
errMsg = result.body.response;
}
Adapter.log.info('Username or Password invalid. ' + errMsg);
await Adapter.setStateAsync('info.connection', false, true);
resolve({
error: true,
msg: 'Could not retrieve token, Error from Tesla: ' + errMsg
});
return;
}
Adapter.log.info('Received a new Token');
let ExpireDate = new Date();
ExpireDate.setSeconds(ExpireDate.getSeconds() + result.body.expires_in);
await Adapter.SetNewToken(result.authToken, result.refreshToken, result.body.expires_in);
await Adapter.setStateAsync('info.connection', true, true);
resolve({
error: false,
authToken: tools.encrypt('rEYbFGzsXW8QBx5', result.authToken),
refreshToken: tools.encrypt('rEYbFGzsXW8QBx5', result.refreshToken),
tokenExpire: ExpireDate.getTime(),
msg: 'Success'
});
});
});
let Vehicles = {};
if(!Response.error){
Vehicles = await new Promise(async resolve => {
let options = {authToken: tools.decrypt('rEYbFGzsXW8QBx5', Response.authToken)};
tjs.vehicles(options, (err, vehicles) => {
if(err){
Adapter.log.info('Invalid answer from Vehicle request. Error: ' + err);
resolve({
error: true,
msg: 'Could not get any vehicle'
});
return;
}
Adapter.log.debug('vehicles Answer:' + JSON.stringify(vehicles));
resolve({
error: false,
msg: 'Success',
vehicles: vehicles
});
});
});
}
Adapter.sendTo(msg.from, msg.command, {success: true, login: Response, vehicles: Vehicles}, msg.callback);
}
if(msg.command === 'getVehicle'){
let Response = await new Promise(async resolve => {
if(msg.message.authToken.length < 10){
resolve({
error: true,
msg: 'Your token is too short'
});
return;
}
let options = {authToken: tools.decrypt('rEYbFGzsXW8QBx5', msg.message.authToken)};
tjs.vehicles(options, (err, vehicles) => {
if(err){
Adapter.log.info('Invalid answer from Vehicle request. Error: ' + err);
resolve({
error: true,
msg: 'Could not get any vehicle'
});
return;
}
Adapter.log.debug('vehicles Answer:' + JSON.stringify(vehicles));
resolve({
error: false,
msg: 'Success',
vehicles: vehicles
});
});
});
Adapter.sendTo(msg.from, msg.command, {success: true, vehicle: Response}, msg.callback);
}
}
async GetNewToken(){
const Adapter = this;
// No token, we try to get a token
if(Adapter.config.teslaUsername.length == 0 || Adapter.config.teslaPassword.length == 0){
Adapter.log.warn("Your authentification token is not valid or expired. Can't get a new token because you did not store username / password. Please request a new token in Adapter Configuration");
return;
}
await tjs.login(Adapter.config.teslaUsername, Adapter.config.teslaPassword, async (err, result) => {
if(!result || !result.response || result.response.statusCode !== 200 || !result.authToken || !result.refreshToken){
Adapter.log.warn('Could not get token, Adapter cant read anything.');
}
else{
await Adapter.SetNewToken(result.authToken, result.refreshToken, result.body.expires_in);
}
});
}
async RefreshToken(){
const Adapter = this;
Adapter.log.debug("Check for Tokens and Expires");
let Expires = new Date(Adapter.config.tokenExpire);
Expires.setDate(Expires.getDate() - 5); // Refresh 5 days before expire
if(Adapter.config.authToken.length > 0 && Expires < new Date()){
tjs.refreshToken(Adapter.config.refreshToken, async (err, result) => {
if(!result || !result.response || result.response.statusCode !== 200 || !result.authToken || !result.refreshToken){
Adapter.log.warn('Could not refresh Token, trying to get a new Token');
await Adapter.setStateAsync('info.connection', false, true);
await Adapter.GetNewToken();
}
else{
await Adapter.SetNewToken(result.authToken, result.refreshToken, result.response.body.expires_in);
}
})
}
else if(Adapter.config.authToken.length === 0){
await Adapter.setStateAsync('info.connection', false, true);
}
else{
await Adapter.setStateAsync('info.connection', true, true);
}
}
async SetNewToken(authToken, refreshToken, tokenExpire){
const Adapter = this;
Adapter.log.info('Setting a new Token');
let ExpireDate = new Date();
ExpireDate.setSeconds(ExpireDate.getSeconds() + Number(tokenExpire));
// Set new token to the settings, Adapter will reboot afterwards...
let obj = await Adapter.getForeignObjectAsync(`system.adapter.${Adapter.namespace}`);
if(!obj){
Adapter.log.error('Could not get Adapter-Config');
return;
}
Adapter.config.authToken = authToken;
Adapter.config.refreshToken = refreshToken;
let c = await this.getForeignObjectAsync(`system.config`);
let secret = c.native.secret;
obj.native.authToken = tools.encrypt(secret, authToken);
obj.native.refreshToken = tools.encrypt(secret, refreshToken);
obj.native.tokenExpire = Adapter.config.tokenExpire = ExpireDate.getTime();
await Adapter.setForeignObjectAsync(`system.adapter.${Adapter.namespace}`, obj);
await Adapter.setStateAsync('info.connection', true, true);
await Adapter.setStateAsync('info.tokenExpire', ExpireDate.toISOString(), true);
}
/**
* Get all info that are available while car is sleeping
* @constructor
*/
async GetStandbyInfo(){
const Adapter = this;
const State = await Adapter.getStateAsync('info.connection');
if(!State){
Adapter.log.warn('You tried to get States, but there is currently no valid Token, please configure Adapter first!');
return;
}
Adapter.log.debug("Getting Standby Info");
await new Promise(async resolve => {
let vehicleIndex = 0;
Adapter.config.vehicles.forEach(function(vehicle, idx){
if(vehicle["id_s"] === Adapter.config.vehicle_id_s){
vehicleIndex = idx;
}
});
let options = {
authToken: Adapter.config.authToken,
carIndex: vehicleIndex
};
let vehicle;
try{
vehicle = await tjs.vehicleAsync(options);
}
catch(err){
Adapter.log.warn('Invalid answer from Vehicle request. Error: ' + err);
return resolve();
}
this.lastOverallRequest = new Date();
Adapter.log.debug('vehicle Answer:' + JSON.stringify(vehicle));
await Adapter.setStateAsync('vehicle.id_s', vehicle.id_s, true);
await Adapter.setStateAsync('vehicle.vin', vehicle.vin, true);
await Adapter.setStateAsync('vehicle.display_name', vehicle.display_name, true);
await Adapter.setStateAsync('command.standby', 'online' !== vehicle.state, true);
await Adapter.setStateAsync('vehicle.option_codes', vehicle.option_codes, true);
await Adapter.setStateAsync('vehicle.color', vehicle.color, true);
if(vehicle.state === 'online' && !this.lastWakeState){
// Car was sleeping before, but woke up now. So we reset the sleep timer
// Only reset if it was sleeping long enough
const Minutes = Math.floor((new Date().getTime() - this.lastTimeWokeUp.getTime()) / 60000);
if(Minutes >= 9 && Minutes < 25){
// Car fell asleep while trying to let him, but then woke up due to some interaction
// As this might be intended, we reset the timer to 9 minutes, this
// give 1 minute to set "inUse", but prevents to let the car awake for another 10 minutes at least.
// If last wake up is < 10, then the process is already running anyway, no need to interrupt.
this.lastTimeWokeUp.setMinutes(new Date().getMinutes() - 9);
}
else if(Minutes >= 25){
// If car woke up more than 25 minutes ago last time we assume this is intended.
// We give the user 5 minutes to interact before car trys to sleep again.
this.lastTimeWokeUp.setMinutes(new Date().getMinutes() - 5);
}
Adapter.log.debug("Reset last wake up time because car was sleeping before, but woke up now.");
}
this.lastWakeState = vehicle.state === 'online';
resolve();
});
}
async WakeItUp(){
const Adapter = this;
const State = await Adapter.getStateAsync('info.connection');
if(!State){
Adapter.log.warn('You tried to wake up the car, but there is currently no valid Token, please configure Adapter first!');
return false;
}
// Check if in standby
await Adapter.GetStandbyInfo();
let standby;
standby = await Adapter.getStateAsync('command.standby');
if(standby && !standby.val && standby.ack){
Adapter.log.debug("Wanted to wake up the car, but car is already awake.");
return true;
}
Adapter.log.debug('Waking up the car...');
let options = {
authToken: Adapter.config.authToken,
vehicleID: Adapter.config.vehicle_id_s
};
try{
Adapter.WakeItUpRetryCount--;
Adapter.lastOverallRequest = new Date();
const data = await tjs.wakeUpAsync(options);
if(data.state != "online") throw 'notOnline';
}
catch(err){
if(Adapter.WakeItUpRetryCount > 0){
Adapter.log.debug("Cant wake up the car, Retrying in 2 Seconds...");
await Sleep(2000);
await Adapter.WakeItUp();
}
else{
Adapter.log.warn("Was not able to wake up the car within 50 Seconds. Car has maybe no internet connection or tesla server is offline. Try to use the app instead.");
Adapter.WakeItUpRetryCount = 30;
}
return false;
}
await Adapter.setStateAsync('command.standby', false, true);
Adapter.WakeItUpRetryCount = 30;
Adapter.log.debug("Wake it Up Successful");
return true;
}
async GetAllInfo(){
const Adapter = this;
const State = await Adapter.getStateAsync('info.connection');
if(!State || !State.val){
Adapter.log.warn('You tried to wake up the car, but there is currently no valid Token, please configure Adapter first!');
return;
}
const awake = await this.WakeItUp();
if(!awake) return;
Adapter.log.debug('Getting all States now');
let options = {
authToken: Adapter.config.authToken,
vehicleID: Adapter.config.vehicle_id_s
};
let vd;
let id_s = await Adapter.getStateAsync('vehicle.id_s');
try{
vd = await new Promise(async (resolve, reject) => {
tjs.vehicleData(options, (err, data) => {
if(err){
Adapter.log.debug("Answer from vehicleState:" + JSON.stringify(data) + JSON.stringify(err));
if(Adapter.config.vehicle_id_s != id_s.val){
Adapter.config.vehicle_id_s = id_s.val;
}
reject(err);
}
else{
resolve(data);
}
});
});
}
catch(error){
Adapter.log.warn('Could not retrieve Data from the Car! Response: ' + error);
return;
}
this.lastOverallRequest = new Date();
Adapter.log.debug("Vehicle Data: " + JSON.stringify(vd));
// km or miles?
let OldDistanceUnit = Adapter.distanceUnit;
Adapter.distanceUnit = vd.gui_settings.gui_distance_units === 'mi/hr' ? 'mi/hr' : 'km/h';
if(OldDistanceUnit !== Adapter.distanceUnit){
await Adapter.installDistanceObjects();
}
// States with in and out
Adapter.setState('command.doorLock', !vd.vehicle_state.locked, true);
Adapter.setState('command.standby', ('online' !== vd.state), true);
Adapter.setState('command.Climate', vd.climate_state.is_climate_on, true);
Adapter.setState('command.SetTemperature', vd.climate_state.driver_temp_setting, true);
Adapter.setState('command.SetChargeLimit', vd.charge_state.charge_limit_soc, true);
Adapter.setState('command.ChargePort', vd.charge_state.charge_port_door_open, true);
Adapter.setState('command.ValetMode', vd.vehicle_state.valet_mode, true);
Adapter.setState('command.SpeedLimit', vd.vehicle_state.speed_limit_mode.active, true);
Adapter.setState('command.SpeedLimitValue', Adapter.m_km(vd.vehicle_state.speed_limit_mode.current_limit_mph), true);
Adapter.setState('command.SentryMode', vd.vehicle_state.sentry_mode, true);
Adapter.setState('command.RemoteStart', vd.vehicle_state.remote_start, true);
Adapter.setState('command.seat_heater_left', vd.climate_state.seat_heater_left, true);
Adapter.setState('command.seat_heater_right', vd.climate_state.seat_heater_right, true);
Adapter.setState('command.steering_wheel_heater', vd.climate_state.steering_wheel_heater || false, true);
if(vd.vehicle_state.fd_window || vd.vehicle_state.fp_window || vd.vehicle_state.rd_window || vd.vehicle_state.rp_window){
Adapter.setState('command.windowVent', true, true);
}
else{
Adapter.setState('command.windowVent', false, true);
}
// all other states
Adapter.setState('chargeState.charging_state', vd.charge_state.charging_state, true);
if(vd.charge_state.charging_state === 'Charging'){
Adapter.setState('command.Charging', true, true);
}
else if(vd.charge_state.charging_state === 'Disconnected' || vd.charge_state.charging_state === 'Stopped'){
Adapter.setState('command.Charging', false, true);
}
Adapter.setState('chargeState.battery_level', vd.charge_state.battery_level, true);
Adapter.setState('chargeState.battery_range', Adapter.m_km(vd.charge_state.battery_range), true);
Adapter.setState('chargeState.est_battery_range', Adapter.m_km(vd.charge_state.est_battery_range), true);
Adapter.setState('chargeState.ideal_battery_range', Adapter.m_km(vd.charge_state.ideal_battery_range), true);
Adapter.setState('chargeState.scheduled_charging_start_time', vd.charge_state.scheduled_charging_start_time, true);
Adapter.setState('chargeState.battery_heater_on', vd.charge_state.battery_heater_on, true);
Adapter.setState('chargeState.minutes_to_full_charge', vd.charge_state.minutes_to_full_charge, true);
Adapter.setState('chargeState.fast_charger_present', vd.charge_state.fast_charger_present, true);
Adapter.setState('chargeState.usable_battery_level', vd.charge_state.usable_battery_level, true);
Adapter.setState('chargeState.charge_energy_added', vd.charge_state.charge_energy_added, true);
Adapter.setState('chargeState.charge_distance_added_rated', Adapter.m_km(vd.charge_state.charge_miles_added_rated), true);
Adapter.setState('chargeState.charger_voltage', vd.charge_state.charger_voltage, true);
Adapter.setState('chargeState.charger_power', vd.charge_state.charger_power, true);
Adapter.setState('chargeState.charge_current_request', vd.charge_state.charge_current_request, true);
Adapter.setState('chargeState.charge_port_cold_weather_mode', vd.charge_state.charge_port_cold_weather_mode, true);
Adapter.setState('climateState.inside_temp', vd.climate_state.inside_temp, true);
Adapter.setState('climateState.outside_temp', vd.climate_state.outside_temp, true);
Adapter.setState('climateState.max_avail_temp', vd.climate_state.max_avail_temp, true);
Adapter.setState('climateState.min_avail_temp', vd.climate_state.min_avail_temp, true);
Adapter.setState('climateState.sun_roof_installed', vd.vehicle_config.sun_roof_installed, true);
Adapter.setState('climateState.front_driver_window', vd.vehicle_state.fd_window == 1, true);
Adapter.setState('climateState.front_passenger_window', vd.vehicle_state.fp_window == 1, true);
Adapter.setState('climateState.rear_driver_window', vd.vehicle_state.rd_window == 1, true);
Adapter.setState('climateState.rear_passenger_window', vd.vehicle_state.rp_window == 1, true);
Adapter.setState('climateState.wiper_blade_heater', vd.climate_state.wiper_blade_heater, true);
Adapter.setState('climateState.side_mirror_heaters', vd.climate_state.side_mirror_heaters, true);
Adapter.setState('climateState.is_preconditioning', vd.climate_state.is_preconditioning, true);
Adapter.setState('climateState.smart_preconditioning', vd.climate_state.smart_preconditioning || false, true);
Adapter.setState('climateState.is_auto_conditioning_on', vd.climate_state.is_auto_conditioning_on, true);
Adapter.setState('climateState.battery_heater', vd.climate_state.battery_heater, true);
Adapter.setState('driveState.shift_state', vd.drive_state.shift_state, true);
Adapter.setState('driveState.speed', Adapter.m_km(vd.drive_state.speed), true);
Adapter.setState('driveState.power', vd.drive_state.power, true);
Adapter.setState('driveState.latitude', vd.drive_state.latitude, true);
Adapter.setState('driveState.longitude', vd.drive_state.longitude, true);
Adapter.setState('driveState.heading', vd.drive_state.heading, true);
Adapter.setState('driveState.gps_as_of', vd.drive_state.gps_as_of * 1000, true);
Adapter.setState('vehicle.is_user_present', vd.vehicle_state.is_user_present, true);
Adapter.setState('vehicle.odometer', Adapter.m_km(vd.vehicle_state.odometer), true);
Adapter.setState('vehicle.homelink_device_count', vd.vehicle_state.homelink_device_count || 0, true);
Adapter.setState('vehicle.homelink_nearby', vd.vehicle_state.homelink_nearby || false, true);
Adapter.setState('vehicle.car_type', vd.vehicle_config.car_type, true);
Adapter.setState('softwareUpdate.download_percentage', vd.vehicle_state.software_update.download_perc, true);
Adapter.setState('softwareUpdate.expected_duration_sec', vd.vehicle_state.software_update.expected_duration_sec, true);
Adapter.setState('softwareUpdate.install_percentage', vd.vehicle_state.software_update.install_perc, true);
Adapter.setState('softwareUpdate.status', vd.vehicle_state.software_update.status, true);
Adapter.setState('softwareUpdate.version', vd.vehicle_state.software_update.version, true);
if(!await Adapter.getStateAsync('command.SetTemperature')){
await Adapter.installDependantObjects(vd);
}
// Late dependant
if(vd.vehicle_config.sun_roof_installed){
Adapter.setState('climateState.sun_roof_percent_open', vd.climate_state.sun_roof_percent_open, true);
Adapter.setState('command.SunRoofVent', 'vent' === vd.climate_state.sun_roof_state, true);
}
if(vd.vehicle_config.rear_seat_heaters === 1){
Adapter.setState('command.seat_heater_rear_center', vd.climate_state.seat_heater_rear_center, true);
Adapter.setState('command.seat_heater_rear_left', vd.climate_state.seat_heater_rear_left, true);
Adapter.setState('command.seat_heater_rear_right', vd.climate_state.seat_heater_rear_right, true);
}
let SpeedLimitMax = await Adapter.getStateAsync('driveState.SpeedLimitMax');
let SpeedLimitMin = await Adapter.getStateAsync('driveState.SpeedLimitMin');
Adapter.setState('driveState.SpeedLimitMax', Adapter.m_km(vd.vehicle_state.speed_limit_mode.max_limit_mph), true);
Adapter.setState('driveState.SpeedLimitMin', Adapter.m_km(vd.vehicle_state.speed_limit_mode.min_limit_mph), true);
if(!SpeedLimitMax
|| !SpeedLimitMin
|| SpeedLimitMax.val !== Adapter.m_km(vd.vehicle_state.speed_limit_mode.max_limit_mph)
|| SpeedLimitMin.val !== Adapter.m_km(vd.vehicle_state.speed_limit_mode.min_limit_mph)
|| OldDistanceUnit !== Adapter.distanceUnit
){
let spmax = Adapter.m_km(vd.vehicle_state.speed_limit_mode.max_limit_mph);
let spmin = Adapter.m_km(vd.vehicle_state.speed_limit_mode.min_limit_mph);
await Adapter.extendObjectAsync('command.SpeedLimitValue', {
type: 'state',
common: {
name: 'Limit car Speed',
desc: 'Min ' + spmin + Adapter.distanceUnit + ', Max ' + spmax + Adapter.distanceUnit,
type: 'number',
role: 'state',
unit: Adapter.distanceUnit,
write: true,
min: spmin,
max: spmax
},
native: {}
});
}
}
m_km(value){
if(this.distanceUnit === 'mi/hr') return value;
else return Math.round(value * 1.60934);
}
km_m(value){
if(this.distanceUnit === 'mi/hr') return value;
else return Math.round(value / 1.60934);
}
async installDistanceObjects(){
const Adapter = this;
const rangeUnit = Adapter.distanceUnit.substr(0, Adapter.distanceUnit.indexOf('/'));
await this.extendObjectAsync('driveState.SpeedLimitMax',
{common: {unit: Adapter.distanceUnit}}
);
await this.extendObjectAsync('driveState.SpeedLimitMin',
{common: {unit: Adapter.distanceUnit}}
);
await this.extendObjectAsync('chargeState.battery_range',
{common: {unit: rangeUnit}}
);
await this.extendObjectAsync('chargeState.est_battery_range',
{common: {unit: rangeUnit}}
);
await this.extendObjectAsync('chargeState.ideal_battery_range',
{common: {unit: rangeUnit}}
);
await this.extendObjectAsync('chargeState.charge_distance_added_rated',
{common: {unit: rangeUnit}}
);
await this.extendObjectAsync('driveState.speed',
{common: {unit: Adapter.distanceUnit}}
);
await this.extendObjectAsync('vehicle.odometer',
{common: {unit: rangeUnit}}
);
}
async installDependantObjects(vd){
await this.extendObjectAsync('command.SetTemperature', {
common: {
min: vd.climate_state.min_avail_temp,
max: vd.climate_state.max_avail_temp
}
});
if(vd.vehicle_config.rear_seat_heaters === 1){
await this.setObjectNotExistsAsync('command.seat_heater_rear_center', {
type: "state",
common: {
name: 'Rear center seat heater',
desc: 'Level of Seat heater (0 = off, 3 = max)',
type: 'number',
role: 'level',
write: true,
min: 0,
max: 3
},
native: {}
});
await this.setObjectNotExistsAsync('command.seat_heater_rear_left', {
type: "state",
common: {
name: 'Rear left seat heater',
desc: 'Level of Seat heater (0 = off, 3 = max)',
type: 'number',
role: 'level',
read: true,
write: true,
min: 0,
max: 3
},
native: {}
});
await this.setObjectNotExistsAsync('command.seat_heater_rear_right', {
type: "state",
common: {
name: 'Rear right seat heater',
desc: 'Level of Seat heater (0 = off, 3 = max)',
type: 'number',
role: 'level',
read: true,
write: true,
min: 0,
max: 3
},
native: {}
});
}
if(vd.vehicle_config.sun_roof_installed){
await this.setObjectNotExistsAsync('command.SunRoofVent', {
type: "state",
common: {
name: 'Sun Roof Vent',
type: 'boolean',
role: 'switch.lock',
write: true
},
native: {}
});
}
if(vd.vehicle_config.sun_roof_installed){
await this.setObjectNotExistsAsync('climateState.sun_roof_percent_open', {
type: "state",
common: {
name: 'Sun Roof % open',
type: 'number',
role: 'level.tilt',
unit: '%',
write: false
},
native: {}
});
}
}
}
// @ts-ignore parent is a valid property on module
if(module.parent){
// Export the constructor in compact mode
module.exports = (options) => new TeslaMotors(options);
}
else{
// otherwise start the instance directly
new TeslaMotors();
}