-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.js
1442 lines (1233 loc) · 41.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 axios = require("axios");
const crypto = require("crypto");
const websocket = require("ws");
const express = require("express");
const os = require("os");
const fs = require("fs");
const path = require("path");
const { execFile } = require("child_process");
const findProcess = require("find-process");
const { downloadRelease } = require("@terascope/fetch-github-release");
const rrLocalConnector = require("./lib/localConnector").localConnector;
const roborock_mqtt_connector = require("./lib/roborock_mqtt_connector").roborock_mqtt_connector;
const rrMessage = require("./lib/message").message;
const vacuum_class = require("./lib/vacuum").vacuum;
const roborockPackageHelper = require("./lib/roborockPackageHelper").roborockPackageHelper;
const deviceFeatures = require("./lib/deviceFeatures").deviceFeatures;
const messageQueueHandler = require("./lib/messageQueueHandler").messageQueueHandler;
let socketServer, webserver;
const systems = {
win32: { x64: "go2rtc_win64.zip" },
linux: {
arm: "go2rtc_linux_arm",
arm64: "go2rtc_linux_arm64",
ia32: "go2rtc_linux_i386",
x64: "go2rtc_linux_amd64",
},
};
let go2rtc;
class Roborock extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: "roborock",
useFormatDate: true,
});
this.on("ready", this.onReady.bind(this));
this.on("stateChange", this.onStateChange.bind(this));
// this.on("objectChange", this.onObjectChange.bind(this));
// this.on("message", this.onMessage.bind(this));
this.on("unload", this.onUnload.bind(this));
this.localKeys = null;
this.roomIDs = {};
this.vacuums = {};
this.socket = null;
this.idCounter = 0;
this.nonce = crypto.randomBytes(16);
this.messageQueue = new Map();
this.roborockPackageHelper = new roborockPackageHelper(this);
this.localConnector = new rrLocalConnector(this);
this.rr_mqtt_connector = new roborock_mqtt_connector(this);
this.message = new rrMessage(this);
this.messageQueueHandler = new messageQueueHandler(this);
this.pendingRequests = new Map();
this.localDevices = {};
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
this.log.info(`Starting adapter. This might take a few minutes depending on your setup. Please wait.`);
this.sentryInstance = this.getPluginInstance("sentry");
this.translations = require(`./admin/i18n/${this.language || "en"}/translations.json`); // fall back to en for test-and-release.yml
await this.setupBasicObjects();
// create new clientID if it doesn't exist yet
let clientID = "";
this.getStateAsync("clientID").then(async (storedClientID) => {
if (storedClientID) {
clientID = storedClientID.val?.toString() ?? "";
} else {
clientID = crypto.randomUUID();
await this.setStateAsync("clientID", { val: clientID, ack: true });
}
});
if (!this.config.username || !this.config.password) {
this.log.error("Username or password missing!");
return;
}
// Initialize the login API (which is needed to get access to the real API).
this.loginApi = axios.create({
baseURL: "https://euiot.roborock.com",
headers: {
header_clientid: crypto.createHash("md5").update(this.config.username).update(clientID).digest().toString("base64"),
},
});
await this.setStateAsync("info.connection", { val: true, ack: true });
// api/v1/getUrlByEmail(email = ...)
const userdata = await this.getUserData(this.loginApi);
try {
this.loginApi.defaults.headers.common["Authorization"] = userdata.token;
} catch (error) {
this.log.error("Failed to login. Most likely wrong token! Deleting HomeData and UserData. Try again! " + error);
if (this.supportsFeature && this.supportsFeature("PLUGINS")) {
if (this.sentryInstance) {
this.sentryInstance.getSentryObject().captureException("Failed to login. Most likely wrong token! Deleting HomeData and UserData. Try again! " + error);
}
}
this.deleteStateAsync("HomeData");
this.deleteStateAsync("UserData");
}
const rriot = userdata.rriot;
// Initialize the real API.
this.api = axios.create({
baseURL: rriot.r.a,
});
this.api.interceptors.request.use((config) => {
try {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(6).toString("base64").substring(0, 6).replace("+", "X").replace("/", "Y");
let url;
if (this.api) {
url = new URL(this.api.getUri(config));
const prestr = [rriot.u, rriot.s, nonce, timestamp, md5hex(url.pathname), /*queryparams*/ "", /*body*/ ""].join(":");
const mac = crypto.createHmac("sha256", rriot.h).update(prestr).digest("base64");
config.headers["Authorization"] = `Hawk id="${rriot.u}", s="${rriot.s}", ts="${timestamp}", nonce="${nonce}", mac="${mac}"`;
}
} catch (error) {
this.log.error("Failed to initialize API. Error: " + error);
if (this.supportsFeature && this.supportsFeature("PLUGINS")) {
if (this.sentryInstance) {
this.sentryInstance.getSentryObject().captureException("Failed to initialize API. Error: " + error);
}
}
}
return config;
});
// Get home details.
try {
const homeDetail = await this.loginApi.get("api/v1/getHomeDetail");
if (homeDetail) {
const homeId = homeDetail.data.data.rrHomeId;
if (this.api) {
const homedata = await this.api.get(`v2/user/homes/${homeId}`);
const homedataResult = homedata.data.result;
const scene = await this.api.get(`user/scene/home/${homeId}`);
await this.setStateAsync("HomeData", {
val: JSON.stringify(homedataResult),
ack: true,
});
// create devices and set states
const products = homedataResult.products;
const devices = homedataResult.devices.concat(homedataResult.receivedDevices);
this.localKeys = new Map(devices.map((device) => [device.duid, device.localKey]));
// this.adapter.log.debug(`initUser test: ${JSON.stringify(Array.from(this.adapter.localKeys.entries()))}`);
await this.rr_mqtt_connector.initUser(userdata);
await this.rr_mqtt_connector.initMQTT_Subscribe();
await this.rr_mqtt_connector.initMQTT_Message();
// store name of each room via ID
const rooms = homedataResult.rooms;
for (const room in rooms) {
const roomID = rooms[room].id;
const roomName = rooms[room].name;
this.roomIDs[roomID] = roomName;
}
this.log.debug("RoomIDs debug: " + JSON.stringify(this.roomIDs));
// reconnect every 3 hours (10800 seconds)
this.reconnectIntervall = this.setInterval(async () => {
this.log.debug("Reconnecting after 3 hours!");
await this.rr_mqtt_connector.reconnectClient();
}, 3600 * 1000);
this.processScene(scene);
this.homedataInterval = this.setInterval(this.updateHomeData.bind(this), 180 * 1000, homeId);
await this.updateHomeData(homeId);
const discoveredDevices = await this.localConnector.getLocalDevices();
await this.createDevices(products, devices);
await this.getNetworkInfo(devices);
// merge udp discovered devices with local devices found via mqtt
Object.entries(discoveredDevices).forEach(([duid, ip]) => {
if (!Object.prototype.hasOwnProperty.call(this.localDevices, duid)) {
this.localDevices[duid] = ip;
}
});
this.log.debug(`localDevices: ${JSON.stringify(this.localDevices)}`);
for (const device in this.localDevices) {
const duid = device;
const ip = this.localDevices[device];
await this.localConnector.createClient(duid, ip);
}
this.initializeDeviceUpdates(products, devices);
// These need to start only after all states have been set
if (this.config.enable_map_creation == true) {
this.startWebserver();
await this.startWebsocketServer();
}
this.log.info(`Starting adapter finished. Lets go!!!!!!!`);
} else {
this.log.info(`Most likely failed to login. Deleting UserData to force new login!`);
await this.deleteStateAsync(`UserData`);
}
}
} catch (error) {
this.log.error("Failed to get home details: " + error.stack);
}
try {
await this.download_go2rtc();
} catch (error) {
this.catchError(`Failed to download go2rtc. ${error.stack}`);
}
try {
this.start_go2rtc(this.vacuums, userdata);
} catch (error) {
this.catchError(`Failed to start go2rtc. ${error.stack}`);
}
}
async getUserData(loginApi) {
// try log in.
const userdata = await loginApi
.post(
"api/v1/login",
new URLSearchParams({
username: this.config.username,
password: this.config.password,
needtwostepauth: "false",
}).toString()
)
.then((res) => res.data.data);
// Alternative without password:
// await loginApi.post("api/v1/sendEmailCode", new url.URLSearchParams({username: username, type: "auth"}).toString()).then(res => res.data);
// // ... get code from user ...
// userdata = await loginApi.post("api/v1/loginWithCode", new url.URLSearchParams({username: username, verifycode: code, verifycodetype: "AUTH_EMAIL_CODE"}).toString()).then(res => res.data.data);
if (userdata == null) {
this.deleteStateAsync("HomeData");
this.deleteStateAsync("UserData");
this.log.error("Error! Failed to login. Maybe wrong username or password?");
return;
}
await this.setStateAsync("UserData", {
val: JSON.stringify(userdata),
ack: true,
});
return userdata;
}
async getNetworkInfo(devices) {
for (const device in devices) {
const duid = devices[device].duid;
const vacuum = this.vacuums[duid];
await vacuum.getParameter(duid, "get_network_info");
}
}
async createDevices(products, devices) {
for (const device in devices) {
const productId = devices[device]["productId"];
// const robotModel = products[device]["model"];
const robotModel = this.getRobotModel(products, productId);
const productCategory = this.getProductCategory(products, productId);
const duid = devices[device].duid;
const name = devices[device].name;
this.vacuums[duid] = new vacuum_class(this, robotModel);
this.vacuums[duid].name = name;
this.vacuums[duid].features = new deviceFeatures(this, devices[device].featureSet, devices[device].newFeatureSet, duid, robotModel, productCategory);
await this.vacuums[duid].features.processSupportedFeatures();
await this.vacuums[duid].setUpObjects(duid);
// sub to all commands of this robot
this.subscribeStates("Devices." + duid + ".commands.*");
this.subscribeStates("Devices." + duid + ".reset_consumables.*");
this.subscribeStates("Devices." + duid + ".programs.startProgram");
}
}
async initializeDeviceUpdates(products, devices) {
this.log.debug(`initializeDeviceUpdates`);
for (const deviceId in devices) {
const device = devices[deviceId];
const duid = device.duid;
const productId = device["productId"];
const robotModel = this.getRobotModel(products, productId);
this.vacuums[duid].mainUpdateInterval = () =>
this.setInterval(this.updateDataMinimumData.bind(this), this.config.updateInterval * 1000, duid, this.vacuums[duid], robotModel);
if (device.online) {
this.log.debug(duid + " online. Starting mainUpdateInterval.");
this.vacuums[duid].mainUpdateInterval(); // actually start mainUpdateInterval()
}
this.vacuums[duid].getStatusIntervall = () =>
this.setInterval(this.getStatus.bind(this), 1000, duid, this.vacuums[duid], robotModel);
if (device.online) {
this.log.debug(duid + " online. Starting getStatusIntervall.");
this.vacuums[duid].getStatusIntervall(); // actually start getStatusIntervall()
// Map updater gets started automatically via getParameter with get_status
}
this.updateDataExtraData(duid, this.vacuums[duid]);
this.updateDataMinimumData(duid, this.vacuums[duid], robotModel);
await this.vacuums[duid].getCleanSummary(duid);
// get map once at start of adapter
await this.vacuums[duid].getMap(duid);
}
}
async processScene(scene) {
if (scene && scene.data.result) {
this.log.debug(`Processing scene ${JSON.stringify(scene.data.result)}`);
const programs = {};
for (const program in scene.data.result) {
const enabled = scene.data.result[program].enabled;
const programID = scene.data.result[program].id;
const programName = scene.data.result[program].name;
const param = scene.data.result[program].param;
this.log.debug(`Processing scene param ${param}`);
const duid = JSON.parse(param).action.items[0].entityId;
if (!programs[duid]) {
programs[duid] = {};
}
programs[duid][programID] = programName;
await this.setObjectNotExistsAsync(`Devices.${duid}.programs`, {
type: "folder",
common: {
name: "Programs",
},
native: {},
});
await this.setObjectAsync(`Devices.${duid}.programs.${programID}`, {
type: "folder",
common: {
name: programName,
},
native: {},
});
const enabledPath = `Devices.${duid}.programs.${programID}.enabled`;
await this.createStateObjectHelper(enabledPath, "enabled", "boolean", null, null, "value");
this.setStateAsync(enabledPath, enabled, true);
const items = JSON.parse(param).action.items;
for (const item in items) {
for (const attribute in items[item]) {
const objectPath = `Devices.${duid}.programs.${programID}.items.${item}.${attribute}`;
let value = items[item][attribute];
const typeOfValue = typeof value;
await this.createStateObjectHelper(objectPath, attribute, typeOfValue, null, null, "value", true, false);
if (typeOfValue == "object") {
value = value.toString();
}
this.setStateAsync(objectPath, value, true);
}
}
}
for (const duid in programs) {
const objectPath = `Devices.${duid}.programs.startProgram`;
await this.createStateObjectHelper(objectPath, "Start saved program", "string", null, Object.keys(programs[duid])[0], "value", true, true, programs[duid]);
}
}
}
async executeScene(sceneID) {
if (this.api) {
try {
await this.api.post(`user/scene/${sceneID.val}/execute`);
} catch (error) {
this.catchError(error.stack, "executeScene");
}
}
}
async startMapUpdater(duid) {
if (!this.vacuums[duid].mapUpdater) {
this.log.debug("Started map updater on robot: " + duid);
this.vacuums[duid].mapUpdater = this.setInterval(() => {
this.vacuums[duid].getMap(duid);
}, this.config.map_creation_interval * 1000);
} else {
this.log.debug(`Map updater on robot: ${duid} already running!`);
}
}
async stopMapUpdater(duid) {
this.log.debug(`Stopping map updater on robot: ${duid}`);
if (this.vacuums[duid].mapUpdater) {
this.clearInterval(this.vacuums[duid].mapUpdater);
this.vacuums[duid].mapUpdater = null;
await this.vacuums[duid].getCleanSummary(duid);
}
}
startWebserver() {
const app = express();
app.use(express.static("lib/map"));
webserver = app.listen(this.config.webserverPort);
webserver.on("error", (error) => {
// This code will run if there was an error starting the server
this.log.error("Error occurred: " + error);
});
}
async stopWebserver() {
webserver.close();
}
async startWebsocketServer() {
socketServer = new websocket.Server({ port: 7906 });
let parameters, robot;
socketServer.on("connection", async (socket) => {
this.socket = socket;
this.log.debug("Websocket client connected");
socket.on("pong", () => {
this.socket = socket;
});
this.webSocketInterval = this.setInterval(() => {
if (!this.socket) {
this.log.debug("Client disconnected. Stopping interval.");
this.clearInterval(this.webSocketInterval);
socket.terminate();
return;
}
this.socket = null;
socket.ping();
}, 1000);
socket.on("message", async (message) => {
const data = JSON.parse(message.toString());
const command = data["command"];
const sendValue = {};
sendValue.parameters = [];
switch (command) {
case "app_zoned_clean":
case "app_goto_target":
case "app_start":
case "app_stop":
case "stop_zoned_clean":
case "app_pause":
case "app_charge":
parameters = data["parameters"];
this.vacuums[data["duid"]].command(data["duid"], command, parameters);
break;
case "getRobots":
sendValue.command = "robotList";
for (const robotID in this.vacuums) {
robot = [robotID, this.vacuums[robotID].name];
sendValue.parameters.push(robot);
}
socket.send(JSON.stringify(sendValue));
break;
case "getMap":
this.vacuums[data["duid"]].getMap(data["duid"]);
break;
case "get_photo":
this.vacuums[data["duid"]].getParameter(data["duid"], "get_photo", data["attribute"]);
break;
case "sniffing_decrypt":
await this.getStateAsync("HomeData")
.then((homedata) => {
if (homedata) {
const homedataVal = homedata.val;
if (typeof homedataVal == "string") {
// this.log.debug("Sniffing message received!");
const homedataParsed = JSON.parse(homedataVal);
this.decodeSniffedMessage(data, homedataParsed.devices);
this.decodeSniffedMessage(data, homedataParsed.receivedDevices);
}
}
})
.catch((error) => {
this.log.error("Failed to decode/decrypt sniffing message. " + error);
if (this.supportsFeature && this.supportsFeature("PLUGINS")) {
if (this.sentryInstance) {
this.sentryInstance.getSentryObject().captureException("Failed to initialize API. Error: " + error);
}
}
});
break;
}
});
socket.on("close", () => {
this.log.debug("Client disconnected");
this.clearInterval(this.webSocketInterval);
this.socket = null;
});
socketServer.on("error", (error) => {
this.log.error("WebSocket Server error: " + error);
});
});
}
async stopWebsocketServer() {
socketServer.close();
}
getRobotModel(products, productID) {
for (const product in products) {
if (products[product].id == productID) {
return products[product].model;
}
}
}
getProductCategory(products, productID) {
for (const product in products) {
if (products[product].id == productID) {
return products[product].category;
}
}
}
startMainUpdateInterval(duid, online) {
const robotModel = this.getRobotModel(duid);
this.vacuums[duid].mainUpdateInterval = () =>
this.setInterval(this.updateDataMinimumData.bind(this), this.config.updateInterval * 1000, duid, this.vacuums[duid], robotModel);
if (online) {
this.log.debug(duid + " online. Starting mainUpdateInterval.");
this.vacuums[duid].mainUpdateInterval(); // actually start mainUpdateInterval()
// Map updater gets startet automatically via getParameter with get_status
}
}
decodeSniffedMessage(data, devices) {
devices.forEach((device) => {
const data_string = JSON.stringify(data);
const parts = data_string.split("/");
const duid_sniffed = parts[parts.length - 1].slice(0, -3);
if (duid_sniffed == device.duid) {
const localKey = JSON.stringify(device.localKey).slice(1, -1);
// this.log.debug("duid_sniffed: " + duid_sniffed);
// this.log.debug("Device duid: " + JSON.stringify(device.duid).slice(1, -1));
// this.log.debug("Device localKey: " + localKey);
const startIndex = data_string.indexOf("'") + 1;
const endIndex = data_string.lastIndexOf("'");
const hex_payload = data_string.substring(startIndex, endIndex);
const msg = Buffer.from(hex_payload, "hex");
// this.log.debug("Sniffing msg: " + msg);
const decodedMessage = this.message._decodeMsg(msg, localKey);
// this.log.debug("decodedMessage: " + JSON.stringify(decodedMessage));
this.log.debug("Decoded sniffing message: " + JSON.stringify(JSON.parse(decodedMessage.payload)));
}
});
}
async onlineChecker(duid) {
const homedata = await this.getStateAsync("HomeData");
// If the home data is not found or if its value is not a string, return false.
if (homedata && typeof homedata.val == "string") {
const homedataJSON = JSON.parse(homedata.val);
const device = homedataJSON.devices.find((device) => device.duid == duid);
const receivedDevice = homedataJSON.receivedDevices.find((device) => device.duid == duid);
// If the device is not found, return false.
if (!device && !receivedDevice) {
return false;
}
return device?.online || receivedDevice?.online;
} else {
return false;
}
}
async isRemoteDevice(duid) {
const homedata = await this.getStateAsync("HomeData");
if (homedata && typeof homedata.val == "string") {
const homedataJSON = JSON.parse(homedata.val);
const receivedDevice = homedataJSON.receivedDevices.find((device) => device.duid == duid);
if (receivedDevice) {
return true;
}
return false;
} else {
return false;
}
}
async getConnector(duid) {
const isRemote = await this.isRemoteDevice(duid);
if (isRemote) {
return this.rr_mqtt_connector;
} else {
return this.localConnector;
}
}
async manageDeviceIntervals(duid) {
return this.onlineChecker(duid)
.then((onlineState) => {
if (!onlineState && this.vacuums[duid].mainUpdateInterval) {
this.clearInterval(this.vacuums[duid].getStatusIntervall);
this.clearInterval(this.vacuums[duid].mainUpdateInterval);
this.clearInterval(this.vacuums[duid].mapUpdater);
} else if (!this.vacuums[duid].mainUpdateInterval) {
this.vacuums[duid].getStatusIntervall();
this.startMainUpdateInterval(duid, onlineState);
}
return onlineState;
})
.catch((error) => {
this.log.error("startStopIntervals " + error);
if (this.supportsFeature && this.supportsFeature("PLUGINS")) {
if (this.sentryInstance) {
this.sentryInstance.getSentryObject().captureException("startStopIntervals " + error);
}
}
return false; // Make device appear as offline on error. Just in case.
});
}
async getStatus(duid, vacuum, robotModel) {
if (robotModel == "roborock.wm.a102") {
// nothing for now
} else if (robotModel == "roborock.wetdryvac.a56") {
await vacuum.getParameter(duid, "get_status");
} else {
await vacuum.getParameter(duid, "get_status");
}
}
async updateDataMinimumData(duid, vacuum, robotModel) {
this.log.debug("Latest data requested");
if (robotModel == "roborock.wm.a102") {
// nothing for now
} else if (robotModel == "roborock.wetdryvac.a56") {
// nothing for now
} else {
await vacuum.getParameter(duid, "get_room_mapping");
await vacuum.getParameter(duid, "get_consumable");
await vacuum.getParameter(duid, "get_server_timer");
await vacuum.getParameter(duid, "get_timer");
await this.checkForNewFirmware(duid);
switch (robotModel) {
case "roborock.vacuum.s4":
case "roborock.vacuum.s5":
case "roborock.vacuum.s5e":
case "roborock.vacuum.a08":
case "roborock.vacuum.a10":
case "roborock.vacuum.a40":
//do nothing
break;
case "roborock.vacuum.s6":
await vacuum.getParameter(duid, "get_carpet_mode");
break;
case "roborock.vacuum.a27":
await vacuum.getParameter(duid, "get_dust_collection_switch_status");
await vacuum.getParameter(duid, "get_wash_towel_mode");
await vacuum.getParameter(duid, "get_smart_wash_params");
await vacuum.getParameter(duid, "app_get_dryer_setting");
break;
default:
await vacuum.getParameter(duid, "get_carpet_mode");
await vacuum.getParameter(duid, "get_carpet_clean_mode");
await vacuum.getParameter(duid, "get_water_box_custom_mode");
}
}
}
async updateDataExtraData(duid, vacuum) {
await vacuum.getParameter(duid, "get_fw_features");
await vacuum.getParameter(duid, "get_multi_maps_list");
}
clearTimersAndIntervals() {
if (this.reconnectIntervall) {
this.clearInterval(this.reconnectIntervall);
}
if (this.homedataInterval) {
this.clearInterval(this.homedataInterval);
}
if (this.commandTimeout) {
this.clearTimeout(this.commandTimeout);
}
this.localConnector.clearLocalDevicedTimeout();
for (const duid in this.vacuums) {
this.clearInterval(this.vacuums[duid].getStatusIntervall);
this.clearInterval(this.vacuums[duid].mainUpdateInterval);
this.clearInterval(this.vacuums[duid].mapUpdater);
}
this.messageQueue.forEach(({ timeout102, timeout301 }) => {
this.clearTimeout(timeout102);
if (timeout301) {
this.clearTimeout(timeout301);
}
});
// Clear the messageQueue map
this.messageQueue.clear();
if (this.webSocketInterval) {
this.clearInterval(this.webSocketInterval);
}
}
checkAndClearRequest(requestId) {
const request = this.messageQueue.get(requestId);
if (!request?.timeout102 && !request?.timeout301) {
this.messageQueue.delete(requestId);
// this.log.debug("Cleared messageQueue");
} else {
this.log.debug(`Not clearing messageQueue. ${request.timeout102} - ${request.timeout301}`);
}
this.log.debug(`Length of message queue: ${this.messageQueue.size}`);
}
async updateHomeData(homeId) {
this.log.debug(`Updating HomeData with homeId: ${homeId}`);
if (this.api) {
try {
const home = await this.api.get(`user/homes/${homeId}`);
const homedata = home.data.result;
if (homedata) {
await this.setStateAsync("HomeData", {
val: JSON.stringify(homedata),
ack: true,
});
this.log.debug("homedata successfully updated");
await this.updateConsumablesPercent(homedata.devices);
await this.updateConsumablesPercent(homedata.receivedDevices);
await this.updateDeviceInfo(homedata.devices);
await this.updateDeviceInfo(homedata.receivedDevices);
} else {
this.log.warn("homedata failed to download");
}
} catch (error) {
this.log.error("Failed to update updateHomeData with error: " + error);
}
}
}
async updateConsumablesPercent(devices) {
for (const device in devices) {
const duid = devices[device].duid;
for (const deviceAttribute in devices[device].deviceStatus) {
const targetConsumable = await this.getObjectAsync(`Devices.${duid}.consumables.${deviceAttribute}`);
if (targetConsumable) {
const val =
devices[device].deviceStatus[deviceAttribute] >= 0 && devices[device].deviceStatus[deviceAttribute] <= 100
? parseInt(devices[device].deviceStatus[deviceAttribute])
: 0;
this.setStateAsync("Devices." + duid + ".consumables." + deviceAttribute, { val: val, ack: true });
}
}
}
}
async updateDeviceInfo(devices) {
for (const device in devices) {
const duid = devices[device].duid;
for (const deviceAttribute in devices[device]) {
if (typeof devices[device][deviceAttribute] != "object") {
let unit;
if (deviceAttribute == "activeTime") {
unit = "h";
devices[device][deviceAttribute] = Math.round(devices[device][deviceAttribute] / 1000 / 60 / 60);
}
await this.setObjectAsync("Devices." + duid + ".deviceInfo." + deviceAttribute, {
type: "state",
common: {
name: deviceAttribute,
type: this.getType(devices[device][deviceAttribute]),
unit: unit,
role: "value",
read: true,
write: false,
},
native: {},
});
this.setStateAsync("Devices." + duid + ".deviceInfo." + deviceAttribute, { val: devices[device][deviceAttribute], ack: true });
}
}
}
}
async checkForNewFirmware(duid) {
const isLocalDevice = !this.isRemoteDevice(duid);
if (isLocalDevice) {
this.log.debug(`getting firmware status`);
if (this.api) {
try {
const update = await this.api.get(`ota/firmware/${duid}/updatev2`);
await this.setObjectNotExistsAsync("Devices." + duid + ".updateStatus", {
type: "folder",
common: {
name: "Update status",
},
native: {},
});
for (const state in update.data.result) {
await this.setObjectNotExistsAsync("Devices." + duid + ".updateStatus." + state, {
type: "state",
common: {
name: state,
type: this.getType(update.data.result[state]),
role: "value",
read: true,
write: false,
},
native: {},
});
this.setStateAsync("Devices." + duid + ".updateStatus." + state, {
val: update.data.result[state],
ack: true,
});
}
} catch (error) {
this.catchError(error, "checkForNewFirmware()", duid);
}
}
}
}
getType(attribute) {
// Get the type of the attribute.
const type = typeof attribute;
// Return the appropriate string representation of the type.
switch (type) {
case "boolean":
return "boolean";
case "number":
return "number";
default:
return "string";
}
}
async createStateObjectHelper(path, name, type, unit, def, role, read, write, states, native = {}) {
const common = {
name: name,
type: type,
unit: unit,
role: role,
read: read,
write: write,
states: states,
};
if (def !== undefined && def !== null && def !== "") {
common.def = def;
}
this.setObjectAsync(path, {
type: "state",
common: common,
native: native,
});
}
async createCommand(duid, command, type, defaultState, states) {
const path = `Devices.${duid}.commands.${command}`;
const name = this.translations[command];
const common = {
name: name,
type: type,
role: "value",
read: true,
write: true,
def: defaultState,
states: states,
};
this.setObjectAsync(path, {
type: "state",
common: common,
native: {},
});
}
async createDeviceStatus(duid, state, type, states, unit) {
const path = `Devices.${duid}.deviceStatus.${state}`;
const name = this.translations[state];
const common = {
name: name,
type: type,
role: "value",
unit: unit,
read: true,
write: false,
states: states,
};
this.setObjectAsync(path, {
type: "state",
common: common,
native: {},
});
}
async createConsumable(duid, state, type, states, unit) {
const path = `Devices.${duid}.consumables.${state}`;
const name = this.translations[state];
const common = {
name: name,
type: type,
role: "value",
unit: unit,
read: true,
write: false,
states: states,
};