forked from isaac-webb/node-mrcool
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCielo.js
709 lines (658 loc) · 19 KB
/
Cielo.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
const querystring = require("querystring");
const fetch = require("node-fetch");
const WebSocket = require("ws");
// Constants
const API_HOST = "api.smartcielo.com";
const API_HTTP_PROTOCOL = "https://";
const PING_INTERVAL = 5 * 60 * 1000;
const DEFAULT_POWER = "off";
const DEFAULT_MODE = "auto";
const DEFAULT_FAN = "auto";
const DEFAULT_TEMPERATURE = 75;
// Exports
class CieloAPIConnection {
// Connection information
#sessionID;
#userID;
#accessToken;
#agent;
#commandCount = 0;
/**
* WebSocket connection to API
*
* @type WebSocket
*/
#ws;
/**
* An array containing all subscribed HVACs
*
* @type CieloHVAC[]
*/
hvacs = [];
// Callbacks
#commandCallback;
#temperatureCallback;
#errorCallback;
/**
* Creates an API connection object that will use the provided callbacks
* once created.
*
* @param {function} commandCallback Callback that executes whenever a
* command is sent
* @param {function} temperatureCallback Callback that executes whenever a
* temperature update is received
* @param {function} errorCallback Callback that executes whenever an error
* is encountered
*/
constructor(commandCallback, temperatureCallback, errorCallback) {
this.#commandCallback = commandCallback;
this.#temperatureCallback = temperatureCallback;
this.#errorCallback = errorCallback;
}
// Connection methods
/**
* Creates the hvacs array using the provided macAddresses and establishes
* the WebSockets connection to the API to receive updates.
*
* @param {string[]} macAddresses MAC addresses of desired HVACs
* @returns {Promise<void>} A Promise containing nothing if resolved, error
* if an error occurs establishing the WebSocket connection
*/
async subscribeToHVACs(macAddresses) {
// Clear the array of any previously subscribed HVACs
this.hvacs = [];
this.#commandCount = 0;
// console.log("accessToken:", this.#accessToken);
// Get the initial information on all devices
const deviceInfo = await this.#getDeviceInfo();
// Ensure the request was successful
if (deviceInfo.error) return Promise.reject(deviceInfo.error);
// Extract the relevant HVACs from the results
for (const device of deviceInfo.data.listDevices) {
if (macAddresses.includes(device.macAddress)) {
let hvac = new CieloHVAC(
device.macAddress,
device.deviceName,
device.applianceId,
device.fwVersion,
device.deviceTypeVersion
);
hvac.updateState(
device.latestAction.power,
device.latestAction.temp,
device.latestAction.mode,
device.latestAction.fanspeed
);
hvac.updateRoomTemperature(device.latEnv.temp);
this.hvacs.push(hvac);
}
}
// Establish the WebSocket connection
return this.#connect();
}
/**
* Obtains authentication and socket connection information from the API.
*
* @param {string} username The username to login with
* @param {string} password The password for the provided username
* @param {string} ip The public IP address of the network the HVACs are on
* @param {string} agent Optional parameter specifying the agent type to
* identify as during the request
* @returns {Promise<void>} A Promise containing nothing if resolved, and
* an error if one occurs during authentication
*/
async establishConnection(username, password, ip, agent) {
// TODO: Add ability to recognize authentication failure
await this.#getAccessTokenAndSessionId(username, password, ip).then(
(data) => {
// console.log(data);
// Save the results
this.#sessionID = data.sessionId;
this.#userID = data.userId;
this.#accessToken = data.accessToken;
return;
}
);
return Promise.resolve();
}
/**
*
* @returns
*/
async #connect() {
// Establish the WebSockets connection
const connectUrl = new URL(
"wss://apiwss.smartcielo.com/websocket/" +
"?sessionId=" +
this.#sessionID +
"&token=" +
this.#accessToken
);
const connectPayload = {
sessionId: this.#agent,
token: this.#accessToken,
};
this.#ws = new WebSocket(connectUrl, connectPayload);
// Start the socket when opened
this.#ws.on("open", () => {
this.#startSocket();
});
// Provide notification to the error callback when the connection is
// closed
this.#ws.on("close", () => {
this.#errorCallback(new Error("Connection Closed."));
});
// Subscribe to status updates
this.#ws.on("message", (message) => {
const data = JSON.parse(message);
if (
data.message_type &&
typeof data.message_type === "string" &&
data.message_type.length > 0 &&
data.action &&
typeof data.action === "object"
) {
const type = data.mid;
const status = data.action;
const roomTemp = data.lat_env_var.temperature;
const thisMac = data.mac_address;
switch (type) {
case "WEB":
this.hvacs.forEach((hvac, index) => {
if (hvac.getMacAddress() === thisMac) {
this.hvacs[index].updateState(
status.power,
status.temp,
status.mode,
status.fanspeed
);
}
});
if (this.#commandCallback !== undefined) {
this.#commandCallback(status);
}
break;
case "Heartbeat":
this.hvacs.forEach((hvac, index) => {
if (hvac.getMacAddress() === thisMac) {
this.hvacs[index].updateRoomTemperature(roomTemp);
}
});
if (this.#temperatureCallback !== undefined) {
this.#temperatureCallback(roomTemp);
}
break;
}
}
});
// Provide notification to the error callback when an error occurs
this.#ws.on("error", (err) => {
this.#errorCallback(err);
});
// Return a promise to notify the user when the socket is open
return new Promise((resolve) => {
this.#ws.on("open", () => {
resolve();
});
});
}
// API Calls
/**
* Extracts the appUser and sessionID values from the hidden HTML inputs on
* the index page.
*
* @returns {Promise<string[]>} An array containing the appUser and
* sessionID
*/
async #getAccessTokenAndSessionId(username, password, ip) {
const appUserUrl = new URL(API_HTTP_PROTOCOL + API_HOST + "/web/login");
const appUserPayload = {
agent: this.#agent,
method: "POST",
headers: {
authority: "api.smartcielo.com",
accept: "application/json, text/plain, */*",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"content-type": "application/json; charset=UTF-8",
origin: "https://home.cielowigle.com",
pragma: "no-cache",
referer: "https://home.cielowigle.com/",
"x-api-key": "7xTAU4y4B34u8DjMsODlEyprRRQEsbJ3IB7vZie4",
},
body: JSON.stringify({
user: {
userId: username,
password: password,
mobileDeviceId: "WEB",
deviceTokenId: "WEB",
appType: "WEB",
appVersion: "1.0",
timeZone: "America/Los_Angeles",
mobileDeviceName: "chrome",
deviceType: "WEB",
ipAddress: ip,
isSmartHVAC: 0,
locale: "en",
},
}),
};
const loginData = await fetch(appUserUrl, appUserPayload)
.then((response) => response.json())
.then((responseJSON) => {
// console.log(responseJSON);
const initialLoginData = responseJSON.data.user;
return initialLoginData;
})
.catch((error) => {
console.error(error);
});
return loginData;
}
/**
* Performs the initial subscription to the API, providing current status of
* all devices in the account.
*
* @param {any} accessCredentials A JSON object containing valid credentials
* @returns {Promise<any>} A Promise containing the JSON response
*/
async #getDeviceInfo() {
const deviceInfoUrl = new URL(
API_HTTP_PROTOCOL + API_HOST + "/web/devices?limit=420"
);
const deviceInfoPayload = {
agent: this.#agent,
method: "GET",
headers: {
authority: "api.smartcielo.com",
accept: "*/*",
"accept-language": "en-US,en;q=0.9",
authorization: this.#accessToken,
"cache-control": "no-cache",
"content-type": "application/json; charset=utf-8",
origin: "https://home.cielowigle.com",
pragma: "no-cache",
referer: "https://home.cielowigle.com/",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "macOS",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
"x-api-key": "7xTAU4y4B34u8DjMsODlEyprRRQEsbJ3IB7vZie4",
},
};
const devicesData = await fetch(deviceInfoUrl, deviceInfoPayload)
.then((response) => response.json())
.then((responseJSON) => {
// console.log("devicesResponse... ", responseJSON.data.listDevices);
return responseJSON;
})
.catch((error) => {
console.error(error);
return;
});
return devicesData;
}
/**
* Starts the WebSocket connection and periodically pings it to keep it
* alive
*
* @returns {Promise<any>} A Promise containing nothing if resolved, and an
* error if rejected
*/
async #startSocket() {
// Periodically ping the socket to keep it alive, seems to be unnessesary with current API
// setInterval(async () => {
// try {
// console.log('pinging socket');
// await this.#pingSocket();
// } catch (error) {
// this.#errorCallback(error);
// }
// }, PING_INTERVAL);
return Promise.resolve();
}
/**
*This refreshes the token by returning a refreshed token, may not be neccesary with the new API
* @returns
*/
async #pingSocket() {
const time = new Date();
const pingUrl = new URL(
"https://api.smartcielo.com/web/token/refresh" +
"?refreshToken=" +
this.#accessToken
);
const pingPayload = {
agent: this.#agent,
headers: {
accept: "application/json, text/plain, */*",
"accept-language": "en-US,en;q=0.9",
authorization: this.#accessToken,
"cache-control": "no-cache",
"content-type": "application/json; charset=utf-8",
pragma: "no-cache",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"x-api-key": "7xTAU4y4B34u8DjMsODlEyprRRQEsbJ3IB7vZie4",
},
referrer: "https://home.cielowigle.com/",
referrerPolicy: "strict-origin-when-cross-origin",
body: null,
method: "GET",
mode: "cors",
credentials: "include",
};
const pingResponse = await fetch(pingUrl, pingPayload)
.then((response) => response.json())
.then((responseJSON) => {
const expires = new Date(responseJSON.data.expiresIn * 1000);
// Calculate the difference between the two dates in minutes
const diffMinutes = Math.round((expires - time) / 60000);
// Log the difference to the console
console.log(
`The refreshed token will expire in ${diffMinutes} minutes.`
);
return responseJSON;
})
.catch((error) => {
console.error(error);
return;
});
return pingResponse;
}
// Utility methods
/**
* Creates an object containing all necessary fields for a command
*
* @param {string} temp Temperature setting
* @param {string} power Power state, on or off
* @param {string} fanspeed Fan speed setting
* @param {string} mode Mode setting, heat, cool, or auto
* @param {string} macAddress Device MAC address
* @param {number} applianceID Appliance ID
* @param {boolean} isAction Whether or not the command is an action
* @param {string} performedAction Value this command is modifying
* @param {string} performedValue Updated value for command
* @param {string} mid Session ID
* @param {string} deviceTypeVersion Device type version
* @param {string} fwVersion Firmware version
* @returns {any}
*/
#buildCommand(
temp,
power,
fanspeed,
mode,
isAction,
performedAction,
performedValue
) {
return {
power: power,
mode: isAction && performedAction === "mode" ? performedValue : mode,
fanspeed: fanspeed,
temp: isAction && performedAction === "temp" ? performedValue : temp,
swing: "auto/stop",
turbo: "off",
light: "off",
oldPower: power,
};
}
/**
* Returns a JSON command payload to execute a parameter change
*
* @param {CieloHVAC} hvac The HVAC to perform the action on
* @param {string} performedAction The parameter to change
* @param {string} performedActionValue The value to change it to
* @returns {string}
*/
#buildCommandPayload(hvac, performedAction, performedActionValue) {
const commandCount = this.#commandCount++;
const result = JSON.stringify({
action: "actionControl",
macAddress: hvac.getMacAddress(),
deviceTypeVersion: hvac.getDeviceTypeVersion() || "BI01",
fwVersion: hvac.getFwVersion(),
actionSource: "WEB",
applianceType: "AC",
applianceId: hvac.getApplianceID(),
actionType: performedAction,
actionValue: performedActionValue,
connection_source: 2,
token: this.#accessToken,
actions: this.#buildCommand(
hvac.getTemperature(),
hvac.getPower(),
hvac.getFanSpeed(),
hvac.getMode(),
true,
performedAction,
performedActionValue
),
mid: this.#sessionID,
application_version: "1.0.0",
ts: Math.round(Date.now() / 1000),
});
return result;
}
/**
* Sends a command to the HVAC
*
* @param {CieloHVAC} hvac The HVAC to perform the action on
* @param {string} performedAction The parameter to change
* @param {string} performedActionValue The value to change it to
* @returns {Promise<void>}
*/
async sendCommand(hvac, performedAction, performedActionValue) {
return new Promise((resolve, reject) => {
this.#ws.send(
this.#buildCommandPayload(hvac, performedAction, performedActionValue),
(error) => {
if (error) {
log.error(error);
reject(error);
} else {
resolve();
}
}
);
});
}
}
class CieloHVAC {
#power = DEFAULT_POWER;
#temperature = DEFAULT_TEMPERATURE;
#mode = DEFAULT_MODE;
#fanSpeed = DEFAULT_FAN;
#roomTemperature = DEFAULT_TEMPERATURE;
#deviceName = "HVAC";
#macAddress = "0000000000";
#deviceTypeVersion = "BI01";
#applianceID = 0;
#fwVersion = "0.0.0";
/**
* Creates a new HVAC with the provided parameters
*
* @param {string} macAddress HVAC's MAC address
* @param {string} deviceName HVAC's name
* @param {number} applianceID Internal appliance ID
* @param {string} fwVersion Firmware version
*/
constructor(
macAddress,
deviceName,
applianceID,
fwVersion,
deviceTypeVersion
) {
this.#macAddress = macAddress;
this.#deviceName = deviceName;
this.#applianceID = applianceID;
this.#fwVersion = fwVersion;
if (deviceTypeVersion.startsWith("BI")) {
this.#deviceTypeVersion = deviceTypeVersion;
} else {
// Defaults back to BI01 if the deviceTypeVersion is not valid
this.#deviceTypeVersion = "BI01";
}
}
/**
* Returns the current power state
*
* @returns {string}
*/
getPower() {
return this.#power;
}
/**
* Returns the current temperature setting
*
* @returns {string}
*/
getTemperature() {
return this.#temperature;
}
/**
* Returns the current mode setting
*
* @returns {string}
*/
getMode() {
return this.#mode;
}
/**
* Returns the current fan speed
*
* @returns {string}
*/
getFanSpeed() {
return this.#fanSpeed;
}
/**
* Returns the current room temperature
*
* @returns {string}
*/
getRoomTemperature() {
return this.#roomTemperature;
}
/**
* Returns the device's MAC address
*
* @returns {string}
*/
getMacAddress() {
return this.#macAddress;
}
/**
* Returns the device type version
* @returns {string}
*/
getDeviceTypeVersion() {
return this.#deviceTypeVersion;
}
/**
* Returns the appliance ID
*
* @returns {number}
*/
getApplianceID() {
return this.#applianceID;
}
/**
* Returns the device's firmware version
*
* @returns {string}
*/
getFwVersion() {
return this.#fwVersion;
}
/**
* Returns the device's name
*
* @returns {string}
*/
getDeviceName() {
return this.#deviceName;
}
/**
* Returns a string representation containing state data
*
* @returns {string}
*/
toString() {
return (
this.#deviceName +
" " +
this.#macAddress +
": " +
[
this.#power,
this.#mode,
this.#fanSpeed,
this.#temperature,
this.#roomTemperature,
].join(", ")
);
}
/**
* Updates the state of the HVAC using the provided parameters
*
* @param {string} power Updated power state, on or off
* @param {string} temperature Updated temperature setting
* @param {string} mode Updated mode, heat, cool, or auto
* @param {string} fanSpeed Updated fan speed
*/
updateState(power, temperature, mode, fanSpeed) {
// TODO: Do some bounds checking
this.#power = power;
this.#temperature = temperature;
this.#mode = mode;
this.#fanSpeed = fanSpeed;
}
/**
* Updates the measured room temperature
*
* @param {string} roomTemperature Updated room temperature
*/
updateRoomTemperature(roomTemperature) {
this.#roomTemperature = roomTemperature;
}
setMode(mode, api) {
return api.sendCommand(this, "mode", mode);
}
setFanSpeed(fanspeed, api) {
return api.sendCommand(this, "fanspeed", fanspeed);
}
setTemperature(temperature, api) {
return api.sendCommand(this, "temp", temperature);
}
/**
* Powers on the HVAC
*
* @param {CieloAPIConnection} api The API to use to execute the command
* @return {Promise<void>}
*/
powerOn(api) {
return api.sendCommand(this, "power", "on");
}
/**
* Powers off the HVAC
*
* @param {CieloAPIConnection} api The API to use to execute the command
* @return {Promise<void>}
*/
powerOff(api) {
return api.sendCommand(this, "power", "off");
}
}
module.exports = {
CieloHVAC: CieloHVAC,
CieloAPIConnection: CieloAPIConnection,
};