forked from skydiver/ewelink-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
296 lines (255 loc) · 6.85 KB
/
Copy pathmain.js
File metadata and controls
296 lines (255 loc) · 6.85 KB
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
const rp = require('request-promise');
const { _get } = require('./lib/helpers');
const {
makeAuthorizationSign,
getDeviceChannelCount,
} = require('./lib/ewelink-helper');
const payloads = require('./lib/payloads');
const { ChangeState } = require('./classes/PowerState');
const { DeviceRaw, CurrentMonth } = require('./classes/PowerUsage');
class eWeLink {
constructor({ region = 'us', email, password, at, apiKey }) {
if (!at && (!email && !password)) {
return { error: 'No credentials provided' };
}
this.region = region;
this.email = email;
this.password = password;
this.at = at;
this.apiKey = apiKey;
}
/**
* Generate eWeLink API URL
*
* @returns {string}
*/
getApiUrl() {
return `https://${this.region}-api.coolkit.cc:8080/api`;
}
/**
* Generate eWeLink WebSocket URL
*
* @returns {string}
*/
getApiWebSocket() {
return `wss://${this.region}-pconnect3.coolkit.cc:8080/api/ws`;
}
/**
* Generate http requests helpers
*
* @param method
* @param uri
* @param body
* @param qs
*
* @returns {Promise<{msg: string, error: *}>}
*/
async makeRequest({ method = 'GET', uri, body = {}, qs = {} }) {
const { at } = this;
if (!at) {
await this.login();
}
const response = await rp({
method,
uri: `${this.getApiUrl()}${uri}`,
headers: { Authorization: `Bearer ${this.at}` },
body,
qs,
json: true,
});
const error = _get(response, 'error', false);
if (error && [401, 402].indexOf(parseInt(error)) !== -1) {
return { error, msg: 'Authentication error' };
}
return response;
}
/**
* Helper to login into eWeLink API
*
* @returns {Promise<{msg: string, error: *}>}
*/
async login() {
const body = payloads.loginPayload({
email: this.email,
password: this.password,
});
let response = await rp({
method: 'POST',
uri: `${this.getApiUrl()}/user/login`,
headers: { Authorization: `Sign ${makeAuthorizationSign(body)}` },
body,
json: true,
});
const error = _get(response, 'error', false);
const region = _get(response, 'region', false);
if (error && [400, 401, 404].indexOf(parseInt(error)) !== -1) {
return { error, msg: 'Authentication error' };
}
if (error && parseInt(error) === 301 && region) {
if (this.region !== region) {
this.region = region;
response = await this.login();
return response;
}
return { error, msg: 'Region does not exist' };
}
this.apiKey = _get(response, 'user.apikey', '');
this.at = _get(response, 'at', '');
return response;
}
/**
* Check if authentication credentials doesn't exists then perform a login
*
* @returns {Promise<void>}
*/
async logIfNeeded() {
if (!this.at) {
await this.login();
}
}
/**
* Get specific device information
*
* @returns {Promise<{msg: string, error: *}>}
*/
async getDevices() {
return this.makeRequest({
uri: '/user/device',
qs: { lang: 'en', getTags: 1 },
});
}
/**
* Get information about all associated devices to account
*
* @param deviceId
*
* @returns {Promise<{msg: string, error: *}>}
*/
async getDevice(deviceId) {
return this.makeRequest({
uri: `/user/device/${deviceId}`,
qs: { lang: 'en', getTags: 1 },
});
}
/**
* Get current power state for a specific device
*
* @param deviceId
* @param channel
*
* @returns {Promise<{state: *, status: string}|{msg: string, error: *}>}
*/
async getDevicePowerState(deviceId, channel = 1) {
const device = await this.getDevice(deviceId);
const error = _get(device, 'error', false);
let state = _get(device, 'params.switch', false);
const switches = _get(device, 'params.switches', false);
const switchesAmount = getDeviceChannelCount(device.uiid || (
(device.extra && device.extra.extra) ?
device.extra.extra.uiid :
0
));
if (error || switchesAmount < channel || (!state && !switches)) {
if (error && parseInt(error) === 401) {
return device;
}
return { error, msg: 'Device does not exist' };
}
if (switches) {
state = switches[channel - 1].switch;
}
return { status: 'ok', state };
}
/**
* Change power state for a specific device
*
* @param deviceId
* @param state
* @param channel
*
* @returns {Promise<{state: *, status: string}|{msg: string, error: *}>}
*/
async setDevicePowerState(deviceId, state, channel = 1) {
const device = await this.getDevice(deviceId);
const error = _get(device, 'error', false);
const status = _get(device, 'params.switch', false);
const switches = _get(device, 'params.switches', false);
const switchesAmount = getDeviceChannelCount(device.uiid || (
(device.extra && device.extra.extra) ?
device.extra.extra.uiid :
0
));
if (error || switchesAmount < channel || (!status && !switches)) {
if (error && parseInt(error) === 401) {
return device;
}
return { error, msg: 'Device does not exist' };
}
let stateToSwitch = state;
if (state === 'toggle') {
stateToSwitch = status === 'on' ? 'off' : 'on';
}
const params = {};
if (switches) {
params.switches = switches;
params.switches[channel - 1].switch = stateToSwitch;
} else {
params.switch = stateToSwitch;
}
return ChangeState.set({
apiUrl: this.getApiWebSocket(),
at: this.at,
apiKey: this.apiKey,
deviceId,
params,
state: stateToSwitch,
});
}
/**
* Toggle power state for a specific device
*
* @param deviceId
* @param channel
*
* @returns {Promise<{state: *, status: string}|{msg: string, error: *}>}
*/
async toggleDevice(deviceId, channel = 1) {
return this.setDevicePowerState(deviceId, 'toggle', channel);
}
/**
* Get device raw power usage
*
* @param deviceId
*
* @returns {Promise<{error: string}|{response: {hundredDaysKwhData: *}, status: string}>}
*/
async getDeviceRawPowerUsage(deviceId) {
await this.logIfNeeded();
return DeviceRaw.get({
apiUrl: this.getApiWebSocket(),
at: this.at,
apiKey: this.apiKey,
deviceId,
});
}
/**
* Get device power usage for current month
*
* @param deviceId
*
* @returns {Promise<{error: string}|{daily: *, monthly: *}>}
*/
async getDevicePowerUsage(deviceId) {
const response = await this.getDeviceRawPowerUsage(deviceId);
const error = _get(response, 'error', false);
const hundredDaysKwhData = _get(response, 'data.hundredDaysKwhData', false);
if (error) {
return response;
}
return {
status: 'ok',
...CurrentMonth.parse({ hundredDaysKwhData }),
};
}
}
module.exports = eWeLink;