-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpowerwall.js
184 lines (172 loc) · 6.66 KB
/
powerwall.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
/* eslint-disable camelcase */
var axios = require('axios');
const Https = require("https");
const unauthenticated_agent = new Https.Agent({
rejectUnauthorized: false,
keepAlive: true,
});
var toughcookie = require('tough-cookie');
var events = require('events');
module.exports = {
Powerwall: class extends events.EventEmitter {
constructor(host) {
super();
this.urlBase = "https://" + host;
this.jar = new toughcookie.CookieJar();
this.http = axios.create({
httpsAgent: unauthenticated_agent,
timeout: 5000,
});
this.authenticated = false;
this.http.interceptors.request.use(config => {
this.jar.getCookies(config.url, {}, (err, cookies) => {
if (err)
return;
config.headers.cookie = cookies.join('; ');
});
return config;
});
this.lastUpdate = 0;
this.history = {};
this.password = null;
this.cookieTimeout = 0;
this.loginTask = null;
this.delayTask = Promise.resolve();
this.updateTask = null;
}
login(password) {
let self = this;
if (!this.loginTask || this.password != password) {
this.loginTask = this.loginInner(password).then(
() => {
self.loginTask = null;
self.delayTask = new Promise(resolve => setTimeout(resolve, 30000));
}
);
}
else {
this.emit("debug", "Login already in progress; deferring to that attempt");
}
return this.loginTask;
}
async loginInner(password) {
let res;
await this.delayTask;
try {
this.emit("debug", "Beginning login attempt");
res = await this.http.post(this.urlBase + '/api/login/Basic',
{
username: "customer",
password: password,
"force_sm_off": false
},
{
headers: {
'Content-Type': 'application/json'
}
}
);
}
catch (e) {
this.authenticated = false;
this.password = null;
if (e.response && e.response.status === 429) {
this.delayTask = new Promise(resolve => setTimeout(resolve, 30000));
return await this.loginInner(password);
}
return this.emit('error', 'login failed: ' + e.toString());
}
if (res.status === 200) {
let foundCookie = false;
if (res.headers['set-cookie'] instanceof Array) {
res.headers['set-cookie'].forEach(c => {
this.jar.setCookie(toughcookie.Cookie.parse(c), res.config.url, () => { });
foundCookie = true;
});
}
else {
this.emit("debug", "Login response Set-Cookie header is a " + typeof res.headers["set-cookie"]);
}
if (foundCookie) {
this.authenticated = true;
this.password = password;
this.cookieTimeout = Date.now() + (60 * 60 * 1000);
return this.emit('login');
}
}
this.password = null;
return this.emit("error", "login failed; " + JSON.stringify(res.headers));
}
update(interval) {
if (!this.updateTask) {
this.updateTask = this.updateInner(interval).then(
() => {
this.updateTask = null;
}
);
}
else {
this.emit("debug", "Update already in progress; deferring to that attempt");
}
return this.updateTask;
}
async updateInner(interval) {
if (!this.authenticated && this.password) {
await this.login(this.password);
}
if (!this.authenticated) {
return this.emit('error', 'not authenticated');
}
let now = Date.now();
if (now > this.cookieTimeout && this.password) {
this.login(this.password)
}
const requestTypes = [
["aggregates", this.urlBase + '/api/meters/aggregates', result => result.data],
["soe", this.urlBase + "/api/system_status/soe", result => (result.data.percentage - 5) / .95],
["grid", this.urlBase + "/api/system_status/grid_status", result => result.data.grid_status],
["operation", this.urlBase + "/api/operation", result => result.data]
];
if (now - this.lastUpdate < interval) {
this.emit("debug", "Using cached data");
for (const [name, url, mapping] of requestTypes) {
this.emit(name, this.history[name]);
}
return;
}
let requests = {};
for (const [name, url, mapping] of requestTypes) {
try {
this.emit("debug", "Requesting " + name);
requests[name] = this.http.get(url);
}
catch (e) {
return this.emit("error", "requests failed to initialize");
}
}
let needAuth = false;
for (const [name, url, mapping] of requestTypes) {
try {
let result = await requests[name];
let data = mapping(result);
this.emit(name, data);
this.history[name] = data;
}
catch (e) {
if (e.response && [401, 403].includes(e.response.status) && this.password) {
needAuth = true;
this.authenticated = false;
}
else {
this.emit("error", name + " failed: " + e.toString());
}
}
}
if (needAuth) {
this.emit("debug", "Tokens rejected; need to log in again");
await this.login(this.password);
await this.updateInner(interval);
}
}
}
}