-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1660 lines (1490 loc) · 52.7 KB
/
index.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 semver = require("semver");
const miio = require("./miio");
const util = require("util");
const callbackifyLib = require("./lib/callbackify");
const safeCall = require("./lib/safeCall");
const noop = () => {};
let homebrideAPI, Service, Characteristic;
const PLUGIN_NAME = "homebridge-xiaomi-roborock-vacuum";
const ACCESSORY_NAME = "XiaomiRoborockVacuum";
const MODELS = require("./models");
const GET_STATE_INTERVAL_MS = 30000; // 30s
module.exports = function (homebridge) {
// Accessory = homebridge.platformAccessory;
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebrideAPI = homebridge;
// UUIDGen = homebridge.hap.uuid;
homebridge.registerAccessory(
PLUGIN_NAME,
ACCESSORY_NAME,
XiaomiRoborockVacuum
);
};
class XiaomiRoborockVacuum {
// From https://github.com/aholstenson/miio/blob/master/lib/devices/vacuum.js#L128
static get cleaningStatuses() {
return ["cleaning", "spot-cleaning", "zone-cleaning", "room-cleaning"];
}
static get errors() {
return {
id1: {
description:
"Try turning the orange laserhead to make sure it isnt blocked.",
},
id2: { description: "Clean and tap the bumpers lightly." },
id3: { description: "Try moving the vacuum to a different place." },
id4: {
description:
"Wipe the cliff sensor clean and move the vacuum to a different place.",
},
id5: { description: "Remove and clean the main brush." },
id6: { description: "Remove and clean the sidebrushes." },
id7: {
description:
"Make sure the wheels arent blocked. Move the vacuum to a different place and try again.",
},
id8: {
description: "Make sure there are no obstacles around the vacuum.",
},
id9: { description: "Install the dustbin and the filter." },
id10: {
description: "Make sure the filter has been tried or clean the filter.",
},
id11: {
description:
"Strong magnetic field detected. Move the device away from the virtual wall and try again",
},
id12: { description: "Battery is low, charge your vacuum." },
id13: {
description:
"Couldnt charge properly. Make sure the charging surfaces are clean.",
},
id14: { description: "Battery malfunctioned." },
id15: { description: "Wipe the wall sensor clean." },
id16: { description: "Use the vacuum on a flat horizontal surface." },
id17: { description: "Sidebrushes malfunctioned. Reboot the system." },
id18: { description: "Fan malfunctioned. Reboot the system." },
id19: { description: "The docking station is not connected to power." },
id20: { description: "unkown" },
id21: {
description:
"Please make sure that the top cover of the laser distance sensor is not pinned.",
},
id22: { description: "Please wipe the dock sensor." },
id23: {
description: "Make sure the signal emission area of dock is clean.",
},
id24: {
description:
"Robot stuck in a blocked area. Manually move it and resume the cleaning.",
},
};
}
constructor(log, config) {
this.log = {
debug: (...args) => (config.silent ? noop() : log.debug(...args)),
info: (...args) => (config.silent ? noop() : log.info(...args)),
warn: (...args) => log.warn(...args),
error: (...args) => log.error(...args),
};
this.config = config;
this.config.name = config.name || "Roborock vacuum cleaner";
this.config.cleanword = config.cleanword || "cleaning";
this.config.pause = config.pause || false;
this.config.pauseWord = config.pauseWord || "Pause";
this.config.findMe = config.findMe || false;
this.config.findMeWord = config.findMeWord || "where are you";
this.config.roomTimeout =
config.roomTimeout == undefined ? 0 : config.roomTimeout;
this.services = {};
// Used to store the latest state to reduce logging
this.cachedState = new Map();
this.device = null;
this.connectingPromise = null;
this.connectRetry = setTimeout(() => void 0, 100); // Noop timeout only to initialise the property
this.getStateInterval = setInterval(() => void 0, GET_STATE_INTERVAL_MS); // Noop timeout only to initialise the property
this.roomIdsToClean = new Set();
if (!this.config.ip) {
throw new Error("You must provide an ip address of the vacuum cleaner.");
}
if (!this.config.token) {
throw new Error("You must provide a token of the vacuum cleaner.");
}
if (this.config.rooms && this.config.autoroom) {
throw new Error(`Both "autoroom" and "rooms" config options can't be used at the same time.\n
Please, use "autoroom" to retrieve the "rooms" config and remove it when not needed.`);
}
// HOMEKIT SERVICES
this.initialiseServices();
// Initialize device
this.connect().catch(() => {
// Do nothing in the catch because this function already logs the error internally and retries after 2 minutes.
});
}
initialiseServices() {
// Make sure `this.device` exists before calling any of the methods
const callbackify = (fn, cb) =>
this.device ? callbackifyLib(fn, cb) : cb(new Error("Not connected yet"));
this.services.info = new Service.AccessoryInformation();
this.services.info
.setCharacteristic(Characteristic.Manufacturer, "Xiaomi")
.setCharacteristic(Characteristic.Model, "Roborock");
this.services.info
.getCharacteristic(Characteristic.FirmwareRevision)
.on("get", (cb) => callbackify(() => this.getFirmware(), cb));
this.services.info
.getCharacteristic(Characteristic.Model)
.on("get", (cb) => callbackify(() => this.device.miioModel, cb));
this.services.info
.getCharacteristic(Characteristic.SerialNumber)
.on("get", (cb) => callbackify(() => this.getSerialNumber(), cb));
this.services.fan = new Service.Fan(this.config.name, "Speed");
if (this.services.fan.setPrimaryService) {
this.services.fan.setPrimaryService(true);
}
this.services.fan
.getCharacteristic(Characteristic.On)
.on("get", (cb) => callbackify(() => this.getCleaning(), cb))
.on("set", (newState, cb) =>
callbackify(() => this.setCleaning(newState), cb)
)
.on("change", (oldState, newState) => {
this.changedPause(newState);
});
this.services.fan
.getCharacteristic(Characteristic.RotationSpeed)
.on("get", (cb) => callbackify(() => this.getSpeed(), cb))
.on("set", (newState, cb) =>
callbackify(() => this.setSpeed(newState), cb)
);
if (this.config.waterBox) {
this.services.waterBox = new Service.Fan(
`${this.config.name} Water Box`,
"Water Box"
);
this.services.waterBox
.getCharacteristic(Characteristic.RotationSpeed)
.on("get", (cb) => callbackify(() => this.getWaterSpeed(), cb))
.on("set", (newState, cb) =>
callbackify(() => this.setWaterSpeed(newState), cb)
);
// We need to handle the ON/OFF characteristic (https://github.com/homebridge-xiaomi-roborock-vacuum/homebridge-xiaomi-roborock-vacuum/issues/284)
this.services.waterBox
.getCharacteristic(Characteristic.On)
.on("get", (cb) =>
// If the speed is over 0%, assume it's ON
callbackify(async () => (await this.getWaterSpeed()) > 0, cb)
)
.on("set", (newState, cb) =>
callbackify(() => {
// Set to 0% (Off) when receiving an OFF request, do nothing otherwise.
if (!newState) {
return this.setCleaning(0);
}
}, cb)
);
}
if (this.config.dustCollection) {
this.services.dustCollection = new Service.Fan(
`${this.config.name} Dust Collection`,
"Dust Collection"
);
this.services.dustCollection
.getCharacteristic(Characteristic.On)
.on("get", (cb) => callbackify(() => this.getDustCollectionState(), cb))
.on("set", (newState, cb) =>
callbackify(() => this.setDustCollectionState(newState), cb)
);
}
this.services.battery = new Service.BatteryService(
`${this.config.name} Battery`
);
this.services.battery
.getCharacteristic(Characteristic.BatteryLevel)
.on("get", (cb) => callbackify(() => this.getBattery(), cb));
this.services.battery
.getCharacteristic(Characteristic.ChargingState)
.on("get", (cb) => callbackify(() => this.getCharging(), cb));
this.services.battery
.getCharacteristic(Characteristic.StatusLowBattery)
.on("get", (cb) => callbackify(() => this.getBatteryLow(), cb));
if (this.config.pause) {
this.services.pause = new Service.Switch(
`${this.config.name} ${this.config.pauseWord}`,
"Pause Switch"
);
this.services.pause
.getCharacteristic(Characteristic.On)
.on("get", (cb) => callbackify(() => this.getPauseState(), cb))
.on("set", (newState, cb) =>
callbackify(() => this.setPauseState(newState), cb)
);
// TODO: Add 'change' status?
}
if (this.config.findMe) {
this.services.findMe = new Service.Switch(
`${this.config.name} ${this.config.findMeWord}`,
"FindMe Switch"
);
this.services.findMe
.getCharacteristic(Characteristic.On)
.on("get", (cb) => callbackify(() => false, cb))
.on("set", (newState, cb) => this.identify(cb));
}
if (this.config.dock) {
this.services.dock = new Service.OccupancySensor(
`${this.config.name} Dock`
);
this.services.dock
.getCharacteristic(Characteristic.OccupancyDetected)
.on("get", (cb) => callbackify(() => this.getDocked(), cb));
}
if (this.config.rooms && !this.config.autoroom) {
for (var i in this.config.rooms) {
this.createRoom(this.config.rooms[i].id, this.config.rooms[i].name);
}
}
// Declare services for rooms in advance, so HomeKit can create the switches
if (this.config.autoroom && Array.isArray(this.config.autoroom)) {
for (const i in this.config.autoroom) {
// Index will be overwritten, when robot is available
this.createRoom(i, this.config.autoroom[i]);
}
}
if (this.config.zones) {
for (var i in this.config.zones) {
this.createZone(this.config.zones[i].name, this.config.zones[i].zone);
}
}
// ADDITIONAL HOMEKIT SERVICES
this.initialiseCareServices();
}
initialiseCareServices() {
// Make sure `this.device` exists before calling any of the methods
const callbackify = (fn, cb) =>
this.device ? callbackifyLib(fn, cb) : cb(new Error("Not connected yet"));
if (this.config.legacyCareSensors) {
Characteristic.CareSensors = function () {
Characteristic.call(
this,
"Care indicator sensors",
"00000101-0000-0000-0000-000000000000"
);
this.setProps({
format: Characteristic.Formats.FLOAT,
unit: "%",
perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY],
});
this.value = this.getDefaultValue();
};
util.inherits(Characteristic.CareSensors, Characteristic);
Characteristic.CareSensors.UUID = "00000101-0000-0000-0000-000000000000";
Characteristic.CareFilter = function () {
Characteristic.call(
this,
"Care indicator filter",
"00000102-0000-0000-0000-000000000000"
);
this.setProps({
format: Characteristic.Formats.FLOAT,
unit: "%",
perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY],
});
this.value = this.getDefaultValue();
};
util.inherits(Characteristic.CareFilter, Characteristic);
Characteristic.CareFilter.UUID = "00000102-0000-0000-0000-000000000000";
Characteristic.CareSideBrush = function () {
Characteristic.call(
this,
"Care indicator side brush",
"00000103-0000-0000-0000-000000000000"
);
this.setProps({
format: Characteristic.Formats.FLOAT,
unit: "%",
perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY],
});
this.value = this.getDefaultValue();
};
util.inherits(Characteristic.CareSideBrush, Characteristic);
Characteristic.CareSideBrush.UUID =
"00000103-0000-0000-0000-000000000000";
Characteristic.CareMainBrush = function () {
Characteristic.call(
this,
"Care indicator main brush",
"00000104-0000-0000-0000-000000000000"
);
this.setProps({
format: Characteristic.Formats.FLOAT,
unit: "%",
perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY],
});
this.value = this.getDefaultValue();
};
util.inherits(Characteristic.CareMainBrush, Characteristic);
Characteristic.CareMainBrush.UUID =
"00000104-0000-0000-0000-000000000000";
Service.Care = function (displayName, subtype) {
Service.call(
this,
displayName,
"00000111-0000-0000-0000-000000000000",
subtype
);
this.addCharacteristic(Characteristic.CareSensors);
this.addCharacteristic(Characteristic.CareFilter);
this.addCharacteristic(Characteristic.CareSideBrush);
this.addCharacteristic(Characteristic.CareMainBrush);
};
util.inherits(Service.Care, Service);
Service.Care.UUID = "00000111-0000-0000-0000-000000000000";
this.services.Care = new Service.Care(`${this.config.name} Care`);
this.services.Care.getCharacteristic(Characteristic.CareSensors).on(
"get",
(cb) => callbackify(() => this.getCareSensors(), cb)
);
this.services.Care.getCharacteristic(Characteristic.CareFilter).on(
"get",
(cb) => callbackify(() => this.getCareFilter(), cb)
);
this.services.Care.getCharacteristic(
Characteristic.CareSideBrush
).on("get", (cb) => callbackify(() => this.getCareSideBrush(), cb));
this.services.Care.getCharacteristic(
Characteristic.CareMainBrush
).on("get", (cb) => callbackify(() => this.getCareMainBrush(), cb));
} else {
this.services.fan
.getCharacteristic(Characteristic.FilterChangeIndication)
.on("get", (cb) =>
callbackify(async () => {
const carePercentages = await Promise.all([
this.getCareSensors(),
this.getCareFilter(),
this.getCareSideBrush(),
]);
return carePercentages.some((item) => item >= 100);
}, cb)
);
this.services.fan
.getCharacteristic(Characteristic.FilterLifeLevel)
.on("get", (cb) =>
callbackify(async () => {
const carePercentages = await Promise.all([
this.getCareSensors(),
this.getCareFilter(),
this.getCareSideBrush(),
]);
return 100 - Math.max(...carePercentages);
}, cb)
);
// Use Homekit's native FilterMaintenance Service
this.services.CareSensors = new Service.FilterMaintenance(
"Care indicator sensors",
"sensors"
);
this.services.CareSensors.getCharacteristic(
Characteristic.FilterChangeIndication
).on("get", (cb) =>
callbackify(async () => {
return (await this.getCareSensors()) >= 100;
}, cb)
);
this.services.CareSensors.getCharacteristic(
Characteristic.FilterLifeLevel
).on("get", (cb) =>
callbackify(async () => 100 - (await this.getCareSensors()), cb)
);
this.services.CareFilter = new Service.FilterMaintenance(
"Care indicator filter",
"filter"
);
this.services.CareFilter.getCharacteristic(
Characteristic.FilterChangeIndication
).on("get", (cb) =>
callbackify(async () => {
return (await this.getCareFilter()) >= 100;
}, cb)
);
this.services.CareFilter.getCharacteristic(
Characteristic.FilterLifeLevel
).on("get", (cb) =>
callbackify(async () => 100 - (await this.getCareFilter()), cb)
);
this.services.CareSideBrush = new Service.FilterMaintenance(
"Care indicator side brush",
"side brush"
);
this.services.CareSideBrush.getCharacteristic(
Characteristic.FilterChangeIndication
).on("get", (cb) =>
callbackify(async () => {
return (await this.getCareSideBrush()) >= 100;
}, cb)
);
this.services.CareSideBrush.getCharacteristic(
Characteristic.FilterLifeLevel
).on("get", (cb) =>
callbackify(async () => 100 - (await this.getCareSideBrush()), cb)
);
this.services.CareMainBrush = new Service.FilterMaintenance(
"Care indicator main brush",
"main brush"
);
this.services.CareMainBrush.getCharacteristic(
Characteristic.FilterChangeIndication
).on("get", (cb) =>
callbackify(async () => {
return (await this.getCareMainBrush()) >= 100;
}, cb)
);
this.services.CareMainBrush.getCharacteristic(
Characteristic.FilterLifeLevel
).on("get", (cb) =>
callbackify(async () => 100 - (await this.getCareMainBrush()), cb)
);
}
}
/**
* Returns if the newValue is different to the previously cached one
*
* @param {string} property
* @param {any} newValue
* @returns {boolean} Whether the newValue is not the same as the previously cached one.
*/
isNewValue(property, newValue) {
const cachedValue = this.cachedState.get(property);
this.cachedState.set(property, newValue);
return cachedValue !== newValue;
}
changedError(robotError) {
if (!robotError) return;
if (!this.isNewValue("error", robotError.id)) return;
this.log.debug(
`DEB changedError | ${this.model} | ErrorID: ${robotError.id}, ErrorDescription: ${robotError.description}`
);
let robotErrorTxt = XiaomiRoborockVacuum.errors[`id${robotError.id}`]
? XiaomiRoborockVacuum.errors[`id${robotError.id}`].description
: `Unknown ERR | errorid can't be mapped. (${robotError.id})`;
if (!`${robotError.description}`.toLowerCase().startsWith("unknown")) {
robotErrorTxt = robotError.description;
}
this.log.warn(
`WAR changedError | ${this.model} | Robot has an ERROR - ${robotError.id}, ${robotErrorTxt}`
);
// Clear the error_code property
this.device.setRawProperty("error_code", 0);
}
changedCleaning(isCleaning) {
if (this.isNewValue("cleaning", isCleaning)) {
this.log.debug(
`MON changedCleaning | ${this.model} | CleaningState is now ${isCleaning}`
);
this.log.info(
`INF changedCleaning | ${this.model} | Cleaning is ${
isCleaning ? "ON" : "OFF"
}.`
);
if (!isCleaning) {
this.roomIdsToClean.clear();
}
}
// We still update the value in Homebridge. If we are calling the changed method is because we want to change it.
this.services.fan
.getCharacteristic(Characteristic.On)
.updateValue(isCleaning);
if (this.config.waterBox) {
this.services.waterBox
.getCharacteristic(Characteristic.On)
.updateValue(isCleaning);
}
}
changedPause(newValue) {
const isCleaning = newValue === true;
if (this.config.pause) {
if (this.isNewValue("pause", isCleaning)) {
this.log.debug(
`MON changedPause | ${this.model} | CleaningState is now ${isCleaning}`
);
this.log.info(
`INF changedPause | ${this.model} | ${
isCleaning ? "Paused possible" : "Paused not possible, no cleaning"
}`
);
}
// We still update the value in Homebridge. If we are calling the changed method is because we want to change it.
this.services.pause
.getCharacteristic(Characteristic.On)
.updateValue(isCleaning === true);
if (this.config.waterBox) {
this.services.waterBox
.getCharacteristic(Characteristic.On)
.updateValue(isCleaning === true);
}
}
}
changedCharging(isCharging) {
const isNewValue = this.isNewValue("charging", isCharging);
if (isNewValue) {
this.log.info(
`MON changedCharging | ${this.model} | ChargingState is now ${isCharging}`
);
this.log.info(
`INF changedCharging | ${this.model} | Charging is ${
isCharging ? "active" : "cancelled"
}`
);
}
// We still update the value in Homebridge. If we are calling the changed method is because we want to change it.
this.services.battery
.getCharacteristic(Characteristic.ChargingState)
.updateValue(
isCharging
? Characteristic.ChargingState.CHARGING
: Characteristic.ChargingState.NOT_CHARGING
);
if (this.config.dock) {
if (isNewValue) {
const msg = isCharging
? "Robot was docked"
: "Robot not anymore in dock";
this.log.info(`INF changedCharging | ${this.model} | ${msg}.`);
}
this.services.dock
.getCharacteristic(Characteristic.OccupancyDetected)
.updateValue(isCharging);
}
}
changedSpeed(speed) {
const isNewValue = this.isNewValue("speed", speed);
if (isNewValue) {
this.log.info(
`MON changedSpeed | ${this.model} | FanSpeed is now ${speed}%`
);
}
const speedMode = this.findSpeedModeFromMiio(speed);
if (typeof speedMode === "undefined") {
this.log.warn(
`WAR changedSpeed | ${this.model} | Speed was changed to ${speed}%, this speed is not supported`
);
} else {
const { homekitTopLevel, name } = speedMode;
if (isNewValue) {
this.log.info(
`INF changedSpeed | ${this.model} | Speed was changed to ${speed}% (${name}), for HomeKit ${homekitTopLevel}%`
);
}
this.services.fan
.getCharacteristic(Characteristic.RotationSpeed)
.updateValue(homekitTopLevel);
}
}
changedBattery(level) {
this.log.debug(
`DEB changedBattery | ${this.model} | BatteryLevel ${level}%`
);
this.services.battery
.getCharacteristic(Characteristic.BatteryLevel)
.updateValue(level);
this.services.battery
.getCharacteristic(Characteristic.StatusLowBattery)
.updateValue(
level < 20
? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
: Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
);
}
async initializeDevice() {
this.log.debug("DEB getDevice | Discovering vacuum cleaner");
const device = await miio.device({
address: this.config.ip,
token: this.config.token,
});
if (device.matches("type:vaccuum")) {
this.device = device;
this.model = this.device.miioModel;
this.services.info.setCharacteristic(Characteristic.Model, this.model);
this.log.info("STA getDevice | Connected to: %s", this.config.ip);
this.log.info("STA getDevice | Model: " + this.device.miioModel);
this.log.info("STA getDevice | State: " + this.device.property("state"));
this.log.info(
"STA getDevice | FanSpeed: " + this.device.property("fanSpeed")
);
this.log.info(
"STA getDevice | BatteryLevel: " + this.device.property("batteryLevel")
);
if (this.config.autoroom) {
if (Array.isArray(this.config.autoroom)) {
await this.getRoomList();
} else {
await this.getRoomMap();
}
}
try {
const serial = await this.getSerialNumber();
this.services.info.setCharacteristic(
Characteristic.SerialNumber,
`${serial}`
);
this.log.info(`STA getDevice | Serialnumber: ${serial}`);
} catch (err) {
this.log.error(`ERR getDevice | get_serial_number | ${err}`);
}
try {
const firmware = await this.getFirmware();
this.firmware = firmware;
this.services.info.setCharacteristic(
Characteristic.FirmwareRevision,
`${firmware}`
);
this.log.info(`STA getDevice | Firmwareversion: ${firmware}`);
} catch (err) {
this.log.error(`ERR getDevice | miIO.info | ${err}`);
}
this.device.on("errorChanged", (error) => this.changedError(error));
this.device.on("stateChanged", (state) => {
if (state.key === "cleaning") {
this.changedCleaning(state.value);
this.changedPause(state.value);
} else if (state.key === "charging") {
this.changedCharging(state.value);
} else if (state.key === "fanSpeed") {
this.changedSpeed(state.value);
} else if (state.key === "batteryLevel") {
this.changedBattery(state.value);
} else {
this.log.debug(
`DEB stateChanged | ${this.model} | Not supported stateChanged event: ${state.key}:${state.value}`
);
}
});
// Now that we know the model, amend the steps in the Rotation speed (for better usability)
const minStep = 100 / (this.findSpeedModes().speed.length - 1);
this.services.fan
.getCharacteristic(Characteristic.RotationSpeed)
.setProps({ minStep: minStep });
await this.getState();
// Refresh the state every 30s so miio maintains a fresh connection (or recovers connection if lost until we fix https://github.com/homebridge-xiaomi-roborock-vacuum/homebridge-xiaomi-roborock-vacuum/issues/81)
clearInterval(this.getStateInterval);
this.getStateInterval = setInterval(
() => this.getState(),
GET_STATE_INTERVAL_MS
);
} else {
const model = (device || {}).miioModel;
this.log.error(
`ERR getDevice | Device "${model}" is not registered as a vacuum cleaner! If you think it should be, please open an issue at https://github.com/homebridge-xiaomi-roborock-vacuum/homebridge-xiaomi-roborock-vacuum/issues/new and provide this line.`
);
this.log.debug(device);
device.destroy();
}
}
async connect() {
if (this.connectingPromise === null) {
// if already trying to connect, don't trigger yet another one
this.connectingPromise = this.initializeDevice().catch((error) => {
this.log.error(
`ERR connect | miio.device, next try in 2 minutes | ${error}`
);
clearTimeout(this.connectRetry);
// Using setTimeout instead of holding the promise. This way we'll keep retrying but not holding the other actions
this.connectRetry = setTimeout(
() => this.connect().catch(() => {}),
120000
);
throw error;
});
}
try {
await this.connectingPromise;
clearTimeout(this.connectRetry);
} finally {
this.connectingPromise = null;
}
}
async ensureDevice(callingMethod) {
try {
if (!this.device) {
const errMsg = `ERR ${callingMethod} | No vacuum cleaner is discovered yet.`;
this.log.error(errMsg);
throw new Error(errMsg);
}
// checking if the device has an open socket it will fail retrieving it if not
// https://github.com/aholstenson/miio/blob/master/lib/network.js#L227
const socket = this.device.handle.api.parent.socket;
this.log.debug(
`DEB ensureDevice | ${this.model} | The socket is still on. Reusing it.`
);
} catch (err) {
if (
/destroyed/i.test(err.message) ||
/No vacuum cleaner is discovered yet/.test(err.message)
) {
this.log.info(
`INF ensureDevice | ${this.model} | The socket was destroyed or not initialised, initialising the device`
);
await this.connect();
} else {
this.log.error(err);
throw err;
}
}
}
async getState() {
try {
await this.ensureDevice("getState");
await this.device.poll();
const state = await this.device.state();
this.log.debug(
`DEB getState | ${this.model} | State %j | Props %j`,
state,
this.device.properties
);
safeCall(state.cleaning, (cleaning) => this.changedCleaning(cleaning));
safeCall(state.charging, (charging) => this.changedCharging(charging));
safeCall(state.fanSpeed, (fanSpeed) => this.changedSpeed(fanSpeed));
safeCall(state.batteryLevel, (batteryLevel) =>
this.changedBattery(batteryLevel)
);
safeCall(state.cleaning, (cleaning) => this.changedPause(cleaning));
if (this.config.waterBox) {
safeCall(state["water_box_mode"], (waterBoxMode) =>
this.changedWaterSpeed(waterBoxMode)
);
}
// No need to throw the error at this point. This are just warnings like (https://github.com/homebridge-xiaomi-roborock-vacuum/homebridge-xiaomi-roborock-vacuum/issues/91)
safeCall(state.error, (error) => this.changedError(error));
} catch (err) {
this.log.error(`ERR getState | %j`, err);
}
}
async getSerialNumber() {
await this.ensureDevice("getSerialNumber");
try {
const serialNumber = await this.device.getSerialNumber();
this.log.info(
`INF getSerialNumber | ${this.model} | Serial Number is ${serialNumber}`
);
return `${serialNumber}`;
} catch (err) {
this.log.warn(
`ERR getSerialNumber | Failed getting the serial number.`,
err
);
return `Unknown`;
}
}
async getFirmware() {
await this.ensureDevice("getFirmware");
try {
const firmware = await this.device.getDeviceInfo();
this.log.info(
`INF getFirmware | ${this.model} | Firmwareversion is ${firmware.fw_ver}`
);
return firmware.fw_ver;
} catch (err) {
this.log.error(
`ERR getFirmware | Failed getting the firmware version.`,
err
);
throw err;
}
}
get isCleaning() {
const status = this.device.property("state");
return XiaomiRoborockVacuum.cleaningStatuses.includes(status);
}
get isPaused() {
const isPaused = this.device.property("state") === "paused";
return isPaused;
}
get isDustCollecting() {
const isDustCollecting = this.device.property("state") === "dust-collection";
return isDustCollecting;
}
async getCleaning() {
try {
const isCleaning = this.isCleaning;
this.log.info(
`INF getCleaning | ${this.model} | Cleaning is ${isCleaning}`
);
return isCleaning;
} catch (err) {
this.log.error(
`ERR getCleaning | Failed getting the cleaning status.`,
err
);
throw err;
}
}
async getCleaningRoom(roomId) {
await this.ensureDevice("getCleaningRoom");
return this.roomIdsToClean.has(roomId);
}
async setCleaning(state) {
await this.ensureDevice("setCleaning");
this.log.info(
`ACT setCleaning | ${this.model} | Set cleaning to ${state}}`
);
try {
if (state && !this.isCleaning) {
// Start cleaning
if (this.roomIdsToClean.size > 0) {
await this.device.cleanRooms(Array.from(this.roomIdsToClean));
this.log.info(
`ACT setCleaning | ${
this.model
} | Start rooms cleaning for rooms ${Array.from(
this.roomIdsToClean
)}, device is in state ${this.device.property("state")}.`
);
} else {
await this.device.activateCleaning();
this.log.info(
`ACT setCleaning | ${
this.model
} | Start full cleaning, device is in state ${this.device.property(
"state"
)}.`
);
}
} else if (!state && (this.isCleaning || this.isPaused)) {
// Stop cleaning
this.log.info(
`ACT setCleaning | ${
this.model
} | Stop cleaning and go to charge, device is in state ${this.device.property(
"state"
)}`
);
await this.device.activateCharging();
this.roomIdsToClean.clear();
}
} catch (err) {
this.log.error(
`ERR setCleaning | ${this.model} | Failed to set cleaning to ${state}`,
err
);
throw err;
}
}
async setCleaningRoom(state, roomId) {
await this.ensureDevice("setCleaning");
try {
if (state && !this.isCleaning && !this.isPaused) {
this.log.info(
`ACT setCleaningRoom | ${this.model} | Enable cleaning Room ID ${roomId}.`
);
// Delete then add, to maintain the correct order.
this.roomIdsToClean.delete(roomId);
this.roomIdsToClean.add(roomId);
this.checkRoomTimeout();
} else if (!state && !this.isCleaning && !this.isPaused) {
this.log.info(
`ACT setCleaningRoom | ${this.model} | Disable cleaning Room ID ${roomId}.`
);
this.roomIdsToClean.delete(roomId);
this.checkRoomTimeout();
}
} catch (err) {
this.log.error(
`ERR setCleaningRoom | ${this.model} | Failed to set cleaning to ${state}`,
err
);
throw err;
}
}
checkRoomTimeout() {
if (this.config.roomTimeout > 0) {
this.log.info(
`ACT setCleaningRoom | ${this.model} | Start timeout to clean rooms`
);
clearTimeout(this._roomTimeout);
if (this.roomIdsToClean.size > 0) {
this._roomTimeout = setTimeout(
this.setCleaning.bind(this, true),
this.config.roomTimeout * 1000
);