-
Notifications
You must be signed in to change notification settings - Fork 0
/
tesla.js
123 lines (96 loc) · 3.81 KB
/
tesla.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
//@ts-check
const { logger } = require('./logger.js');
const config = require('config');
class TeslaAPI {
constructor() {
this.siteId = config.get('tesla.siteId');
this.pwId = config.get('tesla.pwId');
this.brp = config.get('tesla.backupReservePercentage');
this.refreshToken = config.get('tesla.refreshToken');
this.accessToken = undefined;
};
async initialize() {
logger.info("TeslaAPI initializing");
logger.debug('using siteId %s', this.siteId);
logger.debug('using pwId %s', this.pwId);
logger.debug('using refreshToken %s', this.refreshToken);
if (! await this.checkAndRefreshAccessToken()) {
logger.error("Unable to fetch access token. See logs for details.");
return false;
};
return true;
}
async checkAndRefreshAccessToken() {
if (this.isAccessTokenValid()) {
logger.debug("AccessToken is present and still valid.");
return true;
}
let body = JSON.stringify({
grant_type: 'refresh_token',
client_id: 'ownerapi',
refresh_token: this.refreshToken,
scope: 'openid email offline_access'
});
logger.debug('Body for Tesla: %s', body)
const url = "https://auth.tesla.com/oauth2/v3/token"
const response = await fetch(url, {
method: 'POST',
body: body,
headers: {
'content-type': 'application/json; charset=utf-8',
},
});
const json = await response.json();
logger.debug('retrieved JSON from TeslaAPI: %s' , JSON.stringify(json));
this.accessToken = json.access_token;
logger.info("Fetched access token, validating");
return this.isAccessTokenValid();
}
isAccessTokenValid() {
if (this.accessToken === undefined) {
logger.debug("accessToken is undefined");
return false;
}
let atBufferString = Buffer.from(this.accessToken.split('.')[1], 'base64').toString();
logger.debug("AccessToken payload: %s", atBufferString);
let atJson = JSON.parse(atBufferString);
const exp = atJson.exp;
const now = new Date().getTime() / 1000;
logger.debug('expiration of accessToken is %d, now is %d', exp, now);
if (now > exp) {
logger.info("Access Token has expired");
return false;
}
logger.debug("Access Token is valid");
return true;
}
async updateBatteryReservePercentage(targetPercentage) {
logger.info("Updating Battery reserve to %d%", targetPercentage);
await this.checkAndRefreshAccessToken();
let body = JSON.stringify({
backup_reserve_percent: targetPercentage
});
logger.debug('Body for Tesla: %s', body)
const url = "https://owner-api.teslamotors.com/api/1/energy_sites/" + this.siteId + "/backup";
const response = await fetch(url, {
method: 'POST',
body: body,
headers: {
'content-type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + this.accessToken
},
});
const json = await response.json();
logger.debug('retrieved JSON from TeslaAPI: %s' , JSON.stringify(json));
const rc = json.response.code;
logger.debug("response code for battery percentage update is %d", rc);
if (rc != 201) logger.error ("Battery reserve perceentage update failed");
}
setBackupOnlyMode() {
this.updateBatteryReservePercentage(100);
}
setStandbyMode() {
this.updateBatteryReservePercentage(this.brp);
}
}
exports.TeslaAPI = TeslaAPI;