-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.js
1052 lines (895 loc) · 28.9 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
const utils = require("@iobroker/adapter-core");
const { randomBytes } = require("crypto");
const WebSocket = require("ws");
const express = require("express");
const { spawn } = require("child_process");
const go2rtcPath = require("go2rtc-static");
const roborock_package_helper = require("./lib/roborock_package_helper");
const device_features = require("./lib/device_features");
const requests_handler = require("./lib/requests_handler");
const http_api = require("./lib/http_api");
const sniffing = require("./lib/sniffing");
let socketServer, webserver;
const dockingStationStates = ["cleanFluidStatus", "waterBoxFilterStatus", "dustBagStatus", "dirtyWaterBoxStatus", "clearWaterBoxStatus", "isUpdownWaterReady"];
let updateIntervalCount = 0;
class Roborock extends utils.Adapter {
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.socket = null;
this.idCounter = 0;
this.nonce = randomBytes(16);
this.pendingRequests = new Map();
this.http_api = new http_api(this);
this.roborock_package_helper = new roborock_package_helper(this);
this.requests_handler = new requests_handler(this);
this.device_features = new device_features(this);
this.sniffing = new sniffing(this);
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
if (!this.config.username || !this.config.password) {
this.log.error("Username or password missing!");
return;
}
this.sentryInstance = this.getPluginInstance("sentry");
this.translations = require(`./admin/i18n/${this.language || "en"}/translations.json`); // fall back to en for test-and-release.yml
this.log.info(`Starting adapter. This might take a few minutes depending on your setup. Please wait.`);
const clientID = await this.ensureClientID();
await this.http_api.init(clientID);
await this.setupBasicObjects();
await this.requests_handler.init(); // this makes the requests handler connect to mqtt. tcp follows later when IP of each device have been received
// get latest data on start of adapter
const devices = await this.http_api.getDevices();
// need to get network data before processing any other data
for (const device of devices) {
const duid = device.duid;
await this.requests_handler.getParameter(duid, "get_network_info"); // this needs to be called first on start of adapter to get the IP adresses of each device
}
// now network data is present, connect tcp client to devices
await this.requests_handler.initTCP();
// now tcp clients are connected. process any further data
for (const device of devices) {
const duid = device.duid;
await this.createDeviceObjects(device);
await this.requests_handler.getStatus(duid);
this.updateDeviceData(duid);
this.updateConsumablesPercent(duid);
this.updateDeviceInfo(duid);
await this.requests_handler.getCleanSummary(duid);
await this.requests_handler.getMap(duid);
}
await this.processScenes();
this.log.info(`Starting adapter finished. Let's go!!!!!!!`);
// handle requests based on interval here. No separate interval needed anywhere
this.log.debug(`initializing mainUpdateInterval`);
this.mainUpdateInterval = this.setInterval(async () => {
const devices = this.http_api.getDevices();
for (const device of devices) {
if (device.online) {
const duid = device.duid;
try {
// update status every second if websocket is connected or update interval is met
if (this.socket || updateIntervalCount % this.config.updateInterval == 0) {
await this.requests_handler.getStatus(duid);
}
// update device data on interval defined in options
if (updateIntervalCount % this.config.updateInterval == 0) {
this.updateDeviceData(duid);
this.updateConsumablesPercent(duid);
this.updateDeviceInfo(duid);
updateIntervalCount = 0;
}
// update map when needed
const isCleaning = this.requests_handler.isCleaning(duid);
if (isCleaning) this.requests_handler.getMap(duid);
} catch (error) {
this.catchError(error.stack, "mainUpdateInterval", duid);
}
}
}
updateIntervalCount++;
}, 1000);
try {
await this.start_go2rtc();
} catch (error) {
this.catchError(`Failed to start go2rtc. ${error.stack}`);
}
// Start map creation if enabled
if (this.config.enable_map_creation) {
try {
this.startWebserver();
await this.startWebsocketServer();
} catch (error) {
this.catchError(error.stack);
}
}
}
async ensureClientID() {
try {
const clientID = await this.getStateAsync("clientID");
if (!clientID || !clientID.val) {
const randomClientID = crypto.randomUUID();
await this.setState("clientID", { val: randomClientID, ack: true });
this.log.info(`Generated and saved new clientID: ${randomClientID}`);
return randomClientID;
} else {
this.log.info(`Loaded existing clientID: ${clientID.val}`);
return clientID.val;
}
} catch (error) {
this.log.error(`Error ensuring clientID: ${error.message}`);
throw error; // Optional, falls der Fehler weitergereicht werden soll
}
}
async createDeviceObjects(device) {
const duid = device.duid;
const name = device.name;
await this.device_features.processSupportedFeatures(duid);
await this.setObjectAsync("Devices." + duid, {
type: "device",
common: {
name: name,
statusStates: {
onlineId: `${this.name}.${this.instance}.Devices.${duid}.deviceInfo.online`,
},
},
native: {},
});
// sub to all commands of this robot
this.subscribeStates("Devices." + duid + ".commands.*");
this.subscribeStates("Devices." + duid + ".resetConsumables.*");
this.subscribeStates("Devices." + duid + ".programs.startProgram");
this.subscribeStates("Devices." + duid + ".deviceInfo.online");
}
async processScenes() {
const scenes = await this.http_api.getScenes();
if (scenes && scenes?.result) {
const data = scenes.result;
const programs = {};
for (const program in data) {
const enabled = data[program].enabled;
const programID = data[program].id;
const programName = data[program].name;
const param = data[program].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.setState(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.setState(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]);
}
}
}
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 = [];
const devices = this.http_api.getDevices();
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.requests_handler.command(data["duid"], command, parameters);
break;
case "getRobots":
sendValue.command = "robotList";
for (const robotID in devices) {
robot = [robotID, devices.name];
sendValue.parameters.push(robot);
}
socket.send(JSON.stringify(sendValue));
break;
case "getMap":
this.requests_handler.getMap(data["duid"]);
break;
case "get_photo":
this.requests_handler.getParameter(data["duid"], "get_photo", data["attribute"]);
break;
case "sniffing_decrypt":
try {
this.sniffing.decodeSniffedMessage(data, devices);
} 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();
}
async onlineChecker(duid) {
const devices = this.http_api.getDevices();
const device = devices.find((device) => device.duid == duid);
// If the device is not found, return false.
if (!device) {
return false;
}
return device?.online;
}
async updateDeviceData(duid) {
const robotModel = this.http_api.getRobotModel(duid);
if (robotModel == "roborock.wm.a102") {
// nothing for now
} else if (robotModel == "roborock.wetdryvac.a56") {
// nothing for now
} else {
await this.requests_handler.getParameter(duid, "get_fw_features");
await this.requests_handler.getParameter(duid, "get_multi_maps_list");
await this.requests_handler.getParameter(duid, "get_room_mapping");
await this.requests_handler.getParameter(duid, "get_consumable");
await this.requests_handler.getParameter(duid, "get_server_timer");
await this.requests_handler.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 this.requests_handler.getParameter(duid, "get_carpet_mode");
break;
case "roborock.vacuum.a27":
await this.requests_handler.getParameter(duid, "get_dust_collection_switch_status");
await this.requests_handler.getParameter(duid, "get_wash_towel_mode");
await this.requests_handler.getParameter(duid, "get_smart_wash_params");
await this.requests_handler.getParameter(duid, "app_get_dryer_setting");
break;
default:
await this.requests_handler.getParameter(duid, "get_carpet_mode");
await this.requests_handler.getParameter(duid, "get_carpet_clean_mode");
await this.requests_handler.getParameter(duid, "get_water_box_custom_mode");
}
}
}
clearTimersAndIntervals() {
if (this.commandTimeout) {
this.clearTimeout(this.commandTimeout);
}
if (this.mainUpdateInterval) {
this.clearInterval(this.mainUpdateInterval);
}
if (this.requests_handler) {
this.requests_handler.clearQueue();
}
if (this.mainUpdateInterval) {
this.clearInterval(this.mainUpdateInterval);
}
if (this.webSocketInterval) {
this.clearInterval(this.webSocketInterval);
}
}
async updateConsumablesPercent(duid) {
const devices = this.http_api.getDevices();
const device = devices.find((device) => device.duid === duid);
const deviceStatus = device.deviceStatus;
for (const [attribute, value] of Object.entries(deviceStatus)) {
const targetConsumable = await this.getObjectAsync(`Devices.${duid}.consumables.${attribute}`);
if (targetConsumable) {
const val = value >= 0 && value <= 100 ? parseInt(value) : 0;
await this.setState(`Devices.${duid}.consumables.${attribute}`, { val: val, ack: true });
}
}
}
async updateDeviceInfo(duid) {
const devices = this.http_api.getDevices();
const device = devices.find((device) => device.duid === duid);
for (const deviceAttribute in device) {
let value = device[deviceAttribute];
if (typeof value != "object") {
let unit;
if (deviceAttribute == "activeTime") {
unit = "h";
value = Math.round(device[deviceAttribute] / 1000 / 60 / 60);
}
await this.setObjectAsync("Devices." + duid + ".deviceInfo." + deviceAttribute, {
type: "state",
common: {
name: deviceAttribute,
type: this.getType(value),
unit: unit,
role: "value",
read: true,
write: false,
},
native: {},
});
this.setStateChangedAsync("Devices." + duid + ".deviceInfo." + deviceAttribute, { val: value, ack: true });
}
}
}
async checkForNewFirmware(duid) {
this.log.debug(`Checking for new firmware`);
const isLocalDevice = this.requests_handler.isLocalDevice(duid);
if (isLocalDevice) {
const update = await this.http_api.getFirmwareStates(duid);
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.setState("Devices." + duid + ".updateStatus." + state, {
val: update.data.result[state],
ack: true,
});
}
}
}
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 createDockingStationObject(duid) {
for (const state of dockingStationStates) {
const path = `Devices.${duid}.dockingStationStatus.${state}`;
const name = this.translations[state];
await this.setObjectNotExistsAsync(path, {
type: "state",
common: {
name: name,
type: "number",
role: "value",
read: true,
write: false,
states: { 0: "UNKNOWN", 1: "ERROR", 2: "OK" },
},
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,
};
this.setObjectAsync(path, {
type: "state",
common: common,
native: {},
});
}
async createResetConsumables(duid, state) {
const path = `Devices.${duid}.resetConsumables.${state}`;
const name = this.translations[state];
this.setObjectNotExistsAsync(path, {
type: "state",
common: {
name: name,
type: "boolean",
role: "value",
read: true,
write: true,
def: false,
},
native: {},
});
}
async createCleaningRecord(duid, state, type, states, unit) {
let start = 0;
let end = 19;
const robotModel = await this.http_api.getRobotModel(duid);
if (robotModel == "roborock.vacuum.a97") {
start = 1;
end = 20;
}
for (let i = start; i <= end; i++) {
await this.setObjectAsync(`Devices.${duid}.cleaningInfo.records.${i}`, {
type: "folder",
common: {
name: `Cleaning record ${i}`,
},
native: {},
});
this.setObjectAsync(`Devices.${duid}.cleaningInfo.records.${i}.${state}`, {
type: "state",
common: {
name: this.translations[state],
type: type,
role: "value",
unit: unit,
read: true,
write: false,
states: states,
},
native: {},
});
await this.setObjectAsync(`Devices.${duid}.cleaningInfo.records.${i}.map`, {
type: "folder",
common: {
name: "Map",
},
native: {},
});
for (const name of ["mapBase64", "mapBase64Truncated", "mapData"]) {
const objectString = `Devices.${duid}.cleaningInfo.records.${i}.map.${name}`;
await this.createStateObjectHelper(objectString, name, "string", null, null, "value", true, false);
}
}
}
async createCleaningInfo(duid, key, object) {
const path = `Devices.${duid}.cleaningInfo.${key}`;
const name = this.translations[object.name];
this.setObjectAsync(path, {
type: "state",
common: {
name: name,
type: "number",
role: "value",
unit: object.unit,
read: true,
write: false,
},
native: {},
});
}
async createBaseRobotObjects(duid) {
for (const name of ["mapBase64", "mapBase64Truncated", "mapData"]) {
const objectString = `Devices.${duid}.map.${name}`;
await this.createStateObjectHelper(objectString, name, "string", null, null, "value", true, false);
}
this.createNetworkInfoObjects(duid);
}
async createBasicVacuumObjects(duid) {
this.createNetworkInfoObjects(duid);
}
async createBasicWashingMachineObjects(duid) {
this.createNetworkInfoObjects(duid);
}
async createNetworkInfoObjects(duid) {
for (const name of ["ssid", "ip", "mac", "bssid", "rssi"]) {
const objectString = `Devices.${duid}.networkInfo.${name}`;
const objectType = name == "rssi" ? "number" : "string";
await this.createStateObjectHelper(objectString, name, objectType, null, null, "value", true, false);
}
}
async getRobotVersion(duid) {
const devices = this.http_api.getDevices();
for (const device in devices) {
if (devices[device].duid == duid) return devices[device].pv;
}
return "Error in getRobotVersion. Version not found.";
}
getRequestId() {
if (this.idCounter >= 9999) {
this.idCounter = 0;
return this.idCounter;
}
return this.idCounter++;
}
async setupBasicObjects() {
await this.setObjectAsync("Devices", {
type: "folder",
common: {
name: "Devices",
},
native: {},
});
await this.setObjectAsync("UserData", {
type: "state",
common: {
name: "UserData string",
type: "string",
role: "value",
read: true,
write: false,
},
native: {},
});
await this.setObjectAsync("HomeData", {
type: "state",
common: {
name: "HomeData string",
type: "string",
role: "value",
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync("clientID", {
type: "state",
common: {
name: "Client ID",
type: "string",
role: "value",
read: true,
write: false,
},
native: {},
});
await this.setObjectNotExistsAsync("endpoint", {
type: "state",
common: {
name: "MQTT endpoint",
type: "string",
role: "value",
read: true,
write: false,
},
native: {},
});
}
async start_go2rtc() {
const devices = this.http_api.getDevices();
let cameraCount = 0;
const localKeys = this.http_api.getMatchedLocalKeys();
const go2rtcConfig = { streams: {} };
for (const device of devices) {
const duid = device.duid;
if (localKeys) {
const localKey = localKeys.get(duid);
const { u, s, k } = await this.http_api.get_rriot();
if (this.device_features.getFeatureList(duid).isCameraSupported) {
cameraCount++;
go2rtcConfig.streams[duid] = `roborock://mqtt-eu-3.roborock.com:8883?u=${u}&s=${s}&k=${k}&did=${duid}&key=${localKey}&pin=${this.config.cameraPin}`;
}
}
}
if (cameraCount > 0) {
try {
const go2rtcProcess = spawn(go2rtcPath.toString(), ["-config", JSON.stringify(go2rtcConfig)], { shell: false, detached: false, windowsHide: true });
go2rtcProcess.on("error", (error) => {
this.log.error(`Error starting go2rtc: ${error.message}`);
});
go2rtcProcess.stdout.on("data", (data) => {
this.log.debug(`go2rtc output: ${data}`);
});
go2rtcProcess.stderr.on("data", (data) => {
this.log.error(`go2rtc error output: ${data}`);
});
process.on("exit", () => {
go2rtcProcess.kill();
});
} catch (error) {
this.log.error(`Failed to start go2rtc: ${error.message}`);
}
}
}
async catchError(error, attribute, duid) {
const robotModel = duid ? this.http_api.getRobotModel(duid) : "unknown device model";
if (error) {
if (error.toString().includes("retry") || error.toString().includes("locating") || error.toString().includes("timed out after 30 seconds")) {
this.log.warn(`Failed to process ${attribute} on robot ${duid} (${robotModel}): ${error}`);
} else {
this.log.error(`Failed to process ${attribute} on robot ${duid} (${robotModel}): ${error.stack || error}`);
if (this.supportsFeature && this.supportsFeature("PLUGINS")) {
if (this.sentryInstance) {
this.sentryInstance.getSentryObject().captureException(`Error: ${error}`);
}
}
}
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.clearTimersAndIntervals();
this.setState("info.connection", { val: false, ack: true });
callback();
} catch (e) {
this.catchError(e.stack);
callback();
}
}
// If you need to react to object changes, uncomment the following block and the corresponding line in the constructor.
// You also need to subscribe to the objects with `this.subscribeObjects`, similar to `this.subscribeStates`.
// /**
// * Is called if a subscribed object changes
// * @param {string} id
// * @param {ioBroker.Object | null | undefined} obj
// */
// onObjectChange(id, obj) {
// if (obj) {
// // The object was changed
// this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
// } else {
// // The object was deleted
// this.log.info(`object ${id} deleted`);
// }
// }
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state) {
const idParts = id.split(".");
const duid = idParts[3];
const folder = idParts[4];
if (state.ack) {
if (id.endsWith("online")) {
this.log.info(`Device ${duid} is now ${state.val ? "online" : "offline"}`);
}
} else {
const command = idParts[5];
this.log.debug(`onStateChange: ${command} with value: ${state.val}`);
if (state.val == true && typeof state.val == "boolean") {
if (folder == "resetConsumables") {
await this.requests_handler.command(duid, "reset_consumable", command);
} else {
this.requests_handler.command(duid, command);
}
} else if (command == "load_multi_map") {
await this.requests_handler.command(duid, command, [state.val]);
} else if (
command == "app_start" ||
command == "app_segment_clean" ||
command == "app_charge" ||
command == "app_spot" ||
command == "app_zoned_clean" ||
command == "app_goto_target"
) {
switch (command) {
case "app_zoned_clean":
case "app_goto_target":
if (typeof state.val === "string") {
try {
const params = JSON.parse(state.val);
if (command === "app_zoned_clean") {
// Check if params is an array and contains multiple arrays
if (Array.isArray(params) && params.every(Array.isArray)) {
const allZonesValid = params.every((zone) => {
const isCorrectLength = zone.length === 4 || zone.length === 5;
const areAllNumbers = zone.every((item) => typeof item === "number");
const isValidFifth = zone.length !== 5 || (zone[4] >= 1 && zone[4] <= 3);
return isCorrectLength && areAllNumbers && isValidFifth;
});
if (allZonesValid) {
this.requests_handler.command(duid, command, params);
} else {
this.log.error(
`Invalid command parameters for ${command}: ${state.val}. Expected format: [[x1, y1, x2, y2, repeat], [x1, y1, x2, y2, repeat], ...] (where repeat is between 1 and 3)`
);
}
} else {
this.log.error(
`Invalid command parameters for ${command}: ${state.val}. Expected format: [[x1, y1, x2, y2, repeat], [x1, y1, x2, y2, repeat], ...] (where repeat is between 1 and 3)`
);
}
} else if (command === "app_goto_target") {
// For app_goto_target, params should be an array with exactly two numbers
const isCorrectLength = params.length === 2;
const areAllNumbers = params.every((item) => typeof item === "number");
if (isCorrectLength && areAllNumbers) {
this.requests_handler.command(duid, command, params);
} else {
this.log.error(`Invalid command parameters for ${command}: ${state.val}. Expected format: [x, y]`);
}
}
} catch (error) {
this.log.error(`Error parsing JSON for ${command}: ${error}`);
}
}
break;