-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmain.js
More file actions
1912 lines (1799 loc) · 93 KB
/
Copy pathmain.js
File metadata and controls
1912 lines (1799 loc) · 93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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 Json2iob = require("json2iob");
const midea = require("./lib/midea");
const { ACDevice } = require("./lib/midea/devices/ac");
/**
* @param {unknown} err
* @returns {string}
*/
function errMessage(err) {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
return String(err);
}
const STATUS_DESCRIPTIONS = {
powerOn: "Power state",
mode: "Operating mode",
modeIndex: "Operating mode (raw index)",
temperatureSetpoint: "Target temperature",
temperatureUnit: "Temperature unit (0=C, 1=F)",
fanSpeed: "Fan speed (numeric)",
fanSpeedName: "Fan speed (named)",
swing: "Swing direction",
ecoMode: "Eco mode",
turboMode: "Turbo mode",
sleepMode: "Sleep mode",
purify: "Purify / ionizer",
dryClean: "Dry clean",
selfClean: "Self clean",
frostProtection: "Frost protection (8 °C heat)",
indoorTemperature: "Indoor temperature",
outdoorTemperature: "Outdoor temperature",
humiditySetpoint: "Humidity setpoint",
statusCode: "Device status / error code",
powerUsage: "Total power usage",
inError: "Device reports error",
onTimer: "On-timer active",
offTimer: "Off-timer active",
onTimerHours: "On-timer hours",
onTimerMinutes: "On-timer minutes",
offTimerHours: "Off-timer hours",
offTimerMinutes: "Off-timer minutes",
smartEye: "Smart eye / motion sensor",
cosySleep: "Cosy sleep level",
nightLight: "Night light",
ventilation: "Ventilation",
ptcHeater: "PTC auxiliary heater",
auxHeating: "Auxiliary heater (PTC)",
naturalFan: "Natural wind",
naturalWind: "Natural wind",
comfortMode: "Comfort mode",
indirectWind: "Indirect wind (no wind on me)",
breezeless: "Breezeless",
outSilent: "Outdoor silent mode",
indoorHumidity: "Indoor humidity",
screenDisplay: "Screen display level",
screenDisplayAlternate: "Screen display (alternate)",
freshAirPower: "Fresh-air power",
freshAirFanSpeed: "Fresh-air fan speed",
freshAirMode: "Fresh-air mode",
freshAirTemperature: "Fresh-air temperature setpoint",
windLrAngle: "Left/right wind angle",
windUdAngle: "Up/down wind angle",
currentEnergyConsumption: "Current energy consumption",
realtimePower: "Realtime power draw",
totalOperatingConsumption: "Total operating consumption",
// Alternate decodings of the same C1/0x44 reply. Different Midea
// firmware emits the energy bytes in different formats; expose all
// three so the user can pick whichever one matches the SmartHome app
// without changing the codec.
totalEnergyConsumption: "Total energy consumption (BCD)",
totalEnergyConsumptionBinary: "Total energy consumption (Binary u32 / 10)",
totalEnergyConsumptionBinaryKwh: "Total energy consumption (Binary, scaled to kWh)",
totalEnergyConsumptionMsmartBCD: "Total energy consumption (msmart BCD)",
currentEnergyConsumptionBinary: "Current energy consumption (Binary u32 / 10)",
currentEnergyConsumptionBinaryKwh: "Current energy consumption (Binary, scaled to kWh)",
currentEnergyConsumptionMsmartBCD: "Current energy consumption (msmart BCD)",
realtimePowerBinary: "Realtime power (Binary u24 / 10)",
realtimePowerMsmartBCD: "Realtime power (msmart BCD)",
// Extended telemetry from C1 group queries (midea-local#424,
// msmart-ng TurboLed/group1and2Data fork). Group 1: indoor/outdoor
// sensor block. Group 2: indoor fan RPM. Group 7: outdoor unit
// instantaneous power.
compressorFrequency: "Compressor frequency",
outdoorUnitCurrent: "Outdoor unit total current",
outdoorUnitVoltage: "Outdoor unit voltage",
indoorAmbientTemperature: "Indoor ambient temperature (T1)",
indoorCoilTemperature: "Indoor coil temperature (T2)",
outdoorCoilTemperature: "Outdoor coil temperature (T3)",
outdoorAmbientTemperature: "Outdoor ambient temperature (T4)",
compressorDischargeRaw: "Compressor discharge raw (TP)",
indoorFanSpeedRpm: "Indoor fan speed",
outdoorUnitPower: "Outdoor unit power",
outdoorFanSpeedRpm: "Outdoor fan speed",
defrostActive: "Defrost cycle active",
heatingActive: "Heating active (C1/0x45 byte 8 non-zero)",
horizontalLouverAngle: "Horizontal louver angle (deg, Group 11)",
verticalLouverAngle: "Vertical louver angle (deg, Group 11)",
// Additional NewProtocol property toggles surfaced via msmart-ng
// PropertyId enum (devices/AC/command.py).
rateSelect: "Fan-speed precision level",
cascade: "Wind around (cascade) oscillation",
jetCool: "Jet/flash cool one-shot",
presetIeco: "iECO preset",
selfCleanActive: "Self-clean cycle currently running",
electrifyTime: "Electrified runtime",
totalOperatingTime: "Total operating time",
currentOperatingTime: "Current operating time",
childSleep: "Child sleep",
coolFan: "Cool fan",
catchCold: "Catch cold",
peakValleyElectricitySaving: "Peak/valley electricity saving",
feelOwn: "Feel own",
save: "Save energy mode",
lowFrequencyFan: "Low-frequency fan",
light: "Display brightness level",
pmv: "PMV index",
leftrightFan: "Left/right swing active",
updownFan: "Up/down swing active",
fastCheck: "Fast check mode",
timerMode: "Timer mode",
resume: "Resume after power loss",
dustFull: "Dust filter full",
downWindControl: "Down wind control (UD)",
downWindControlLR: "Down wind control (LR)",
dualControl: "Dual setpoint control",
windBlowing: "Wind blowing",
smartWind: "Smart wind",
braceletControl: "Bracelet control",
braceletSleep: "Bracelet sleep",
keepWarm: "Keep warm",
online: "Device reachable on LAN",
targetHumidity: "Target humidity",
currentHumidity: "Current humidity",
tankLevel: "Water tank level (%)",
tankFull: "Water tank full",
tankWarningLevel: "Tank warning threshold",
defrosting: "Defrosting active",
ionMode: "Ion / anion mode",
pumpSwitch: "Drain pump on",
pumpSwitchFlag: "Drain pump disabled",
filterIndicator: "Filter needs cleaning",
verticalSwing: "Vertical swing active",
horizontalSwing: "Horizontal swing active",
errorCode: "Error code",
pm25: "PM2.5 air quality",
dust: "Dust level",
iMode: "iMode active",
modeFc: "Mode FC sub-state",
rareShow: "Rare-show indicator",
dustTime: "Dust filter runtime",
displayClass: "Display class",
lightClass: "Light class",
lightValue: "Light value",
};
const STATUS_UNITS = {
temperatureSetpoint: "°C",
indoorTemperature: "°C",
outdoorTemperature: "°C",
humiditySetpoint: "%",
targetHumidity: "%",
currentHumidity: "%",
tankLevel: "%",
tankWarningLevel: "%",
powerUsage: "kWh",
currentEnergyConsumption: "kWh",
totalOperatingConsumption: "kWh",
realtimePower: "W",
totalEnergyConsumption: "kWh",
totalEnergyConsumptionBinary: "kWh",
totalEnergyConsumptionBinaryKwh: "kWh",
totalEnergyConsumptionMsmartBCD: "kWh",
currentEnergyConsumptionBinary: "kWh",
currentEnergyConsumptionBinaryKwh: "kWh",
currentEnergyConsumptionMsmartBCD: "kWh",
realtimePowerBinary: "W",
realtimePowerMsmartBCD: "W",
compressorFrequency: "Hz",
outdoorUnitCurrent: "A",
outdoorUnitVoltage: "V",
indoorAmbientTemperature: "°C",
indoorCoilTemperature: "°C",
outdoorCoilTemperature: "°C",
outdoorAmbientTemperature: "°C",
indoorFanSpeedRpm: "rpm",
outdoorFanSpeedRpm: "rpm",
outdoorUnitPower: "W",
electrifyTime: "min",
totalOperatingTime: "min",
currentOperatingTime: "min",
onTimerHours: "h",
offTimerHours: "h",
onTimerMinutes: "min",
offTimerMinutes: "min",
};
const STATUS_ROLES = {
// Temperatures
indoorTemperature: "value.temperature",
outdoorTemperature: "value.temperature",
indoorAmbientTemperature: "value.temperature",
indoorCoilTemperature: "value.temperature",
outdoorCoilTemperature: "value.temperature",
outdoorAmbientTemperature: "value.temperature",
freshAirTemperature: "value.temperature",
// Humidity
indoorHumidity: "value.humidity",
currentHumidity: "value.humidity",
// Energy / power
realtimePower: "value.power",
realtimePowerBinary: "value.power",
realtimePowerMsmartBCD: "value.power",
outdoorUnitPower: "value.power",
totalEnergyConsumption: "value.power.consumption",
totalEnergyConsumptionBinary: "value.power.consumption",
totalEnergyConsumptionBinaryKwh: "value.power.consumption",
totalEnergyConsumptionMsmartBCD: "value.power.consumption",
currentEnergyConsumption: "value.power.consumption",
currentEnergyConsumptionBinary: "value.power.consumption",
currentEnergyConsumptionBinaryKwh: "value.power.consumption",
currentEnergyConsumptionMsmartBCD: "value.power.consumption",
powerUsage: "value.power.consumption",
totalOperatingConsumption: "value.power.consumption",
// Electrical
outdoorUnitVoltage: "value.voltage",
outdoorUnitCurrent: "value.current",
compressorFrequency: "value",
// Indicators
inError: "indicator.alarm",
defrostActive: "indicator",
defrosting: "indicator",
dustFull: "indicator.maintenance",
filterIndicator: "indicator.maintenance",
tankFull: "indicator.alarm",
selfCleanActive: "indicator",
online: "indicator.reachable",
// Tank
tankLevel: "value",
// Air quality
pm25: "value",
dust: "value",
// Fan RPM
indoorFanSpeedRpm: "value",
outdoorFanSpeedRpm: "value",
};
const STATUS_STATE_ENUMS = {
mode: { AUTO: "Auto", COOL: "Cool", DRY: "Dry", HEAT: "Heat", FAN_ONLY: "Fan only", set: "Set", continuity: "Continuity", dry_clothes: "Dry clothes", dry_shoes: "Dry shoes", fan: "Fan", manual: "Manual", continuous: "Continuous", "living-room": "Living room", "bed-room": "Bed room", kitchen: "Kitchen", sleep: "Sleep" },
fanSpeedName: { SILENT: "Silent", LOW: "Low", MEDIUM: "Medium", HIGH: "High", FULL: "Full", AUTO: "Auto", CUSTOM: "Custom" },
swing: { STATIONARY: "Stationary", VERTICAL: "Vertical", HORIZONTAL: "Horizontal", BOTH: "Both" },
temperatureUnit: { 0: "Celsius", 1: "Fahrenheit" },
};
const CAPABILITY_DESCRIPTIONS = {
activeClean: "Active clean function",
autoMode: "Auto mode supported",
autoSetHumidity: "Automatic humidity setting",
breezeAway: "Breeze-Away supported",
breezeControl: "Breeze control supported",
breezeMild: "Breeze-Mild supported",
breezeless: "Breezeless supported",
buzzer: "Buzzer supported",
coolMode: "Cool mode supported",
decimals: "Half-degree resolution",
downNoWindFeel: "Down-no-wind-feel supported",
dryMode: "Dry mode supported",
ecoMode: "Eco mode supported",
electricAuxHeating: "Electric auxiliary heating",
fanSpeedControl: "Fan speed control supported",
filterReminder: "Filter cleaning reminder",
flashCool: "Flash cool",
frostProtectionMode: "Frost protection (8 °C heat)",
hasAutoClearHumidity: "Auto-clear humidity supported",
hasHandWind: "Hand wind supported",
heatMode: "Heat mode supported",
horizontalSwingAngle: "Horizontal swing angle adjustable",
ieco: "iECO supported",
indoorHumidity: "Indoor humidity sensor present",
leftrightFan: "Left/right swing supported",
lightControl: "Display light control",
manualSetHumidity: "Manual humidity setting",
maxTempAuto: "Maximum auto-mode setpoint",
maxTempCool: "Maximum cool-mode setpoint",
maxTempHeat: "Maximum heat-mode setpoint",
minTempAuto: "Minimum auto-mode setpoint",
minTempCool: "Minimum cool-mode setpoint",
minTempHeat: "Minimum heat-mode setpoint",
nestCheck: "Nest-check capability",
nestNeedChange: "Nest needs change",
oneKeyNoWindOnMe: "One-key no wind on me",
outSilent: "Outdoor silent mode",
auxFanSpeed: "Aux fan speed control",
auxHeatFanSpeed: "Aux heat fan speed control",
auxHeatMode: "Aux heat mode",
auxMode: "Aux-only mode",
freshAir: "Fresh-air ventilation",
fanSilent: "Fan silent level",
fanLow: "Fan low level",
fanMedium: "Fan medium level",
fanHigh: "Fan high level",
fanAuto: "Fan auto level",
fanCustom: "Fan custom level",
powerCal: "Power calculation",
powerCalSetting: "Power calculation setting",
rateSelect: "Rate select",
selfClean: "Self clean",
silkyCool: "Silky cool",
smartEye: "Smart eye",
specialEco: "Special eco",
turboCool: "Turbo cool",
turboHeat: "Turbo heat",
unitChangeable: "Temperature unit changeable",
updownFan: "Up/down swing supported",
upNoWindFeel: "Up no-wind feel",
verticalSwingAngle: "Vertical swing angle adjustable",
windOffMe: "Wind off me",
windOnMe: "Wind on me",
};
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const AC_CONTROLS = [
{ id: "powerOn", common: { name: "Power on/off", type: "boolean", role: "switch.power", read: true, write: true, def: false } },
{ id: "mode", common: { name: "Operating mode", type: "string", role: "level.mode.airconditioner", read: true, write: true, def: "AUTO", states: { AUTO: "Auto", COOL: "Cool", DRY: "Dry", HEAT: "Heat", FAN_ONLY: "Fan only" } } },
{ id: "temperatureSetpoint", common: { name: "Target temperature", type: "number", role: "level.temperature", unit: "°C", read: true, write: true, min: 16, max: 31, def: 21 } },
{ id: "temperatureUnit", common: { name: "Temperature unit", type: "string", role: "state", read: true, write: true, def: "celsius", states: { celsius: "Celsius", fahrenheit: "Fahrenheit" } } },
{ id: "fanSpeed", common: { name: "Fan speed (numeric)", type: "number", role: "level.fan", read: true, write: true, min: 0, max: 102, def: 102 } },
{ id: "fanSpeedName", common: { name: "Fan speed (named)", type: "string", role: "level.mode.fan", read: true, write: true, def: "AUTO", states: { SILENT: "Silent", LOW: "Low", MEDIUM: "Medium", HIGH: "High", FULL: "Full", AUTO: "Auto" } } },
{ id: "swing", common: { name: "Swing", type: "string", role: "level.mode.swing", read: true, write: true, def: "STATIONARY", states: { STATIONARY: "Stationary", VERTICAL: "Vertical", HORIZONTAL: "Horizontal", BOTH: "Both" } } },
{ id: "ecoMode", common: { name: "Eco mode", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "turboMode", common: { name: "Turbo mode", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "sleepMode", common: { name: "Sleep mode", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "save", common: { name: "Power saving (Quiet Sleep)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "purify", common: { name: "Purify / ionizer", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "dryClean", common: { name: "Dry clean", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "selfClean", common: { name: "Self clean (app: Selbstreinigung)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "anion", common: { name: "Anion / ionizer", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "sound", common: { name: "Buzzer (persistent)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "promptTone", common: { name: "Prompt tone (beep on command)", type: "boolean", role: "switch", read: false, write: true, def: false } },
{ id: "jetCool", common: { name: "Jet / flash cool", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "cascade", common: { name: "Wind around (cascade)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "presetIeco", common: { name: "iECO preset", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "rateSelect", common: { name: "Fan-speed precision level", type: "number", role: "level", read: true, write: true, min: 0, max: 100, def: 0 } },
{ id: "frostProtection", common: { name: "Frost protection (8 °C heat)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "smartEye", common: { name: "Smart eye / motion sensor", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "auxHeating", common: { name: "Auxiliary heater (PTC)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "naturalWind", common: { name: "Natural wind", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "comfortMode", common: { name: "Comfort mode", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "indirectWind", common: { name: "Indirect wind (no wind on me)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "breezeless", common: { name: "Breezeless", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "outSilent", common: { name: "Outdoor silent mode (~6 dB quieter, PortaSplit)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "screenDisplayAlternate", common: { name: "Screen display (alternate)", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "freshAirPower", common: { name: "Fresh-air power", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "freshAirFanSpeed", common: { name: "Fresh-air fan speed (0–100)", type: "number", role: "level.fan", read: true, write: true, min: 0, max: 100, def: 0 } },
{ id: "windLrAngle", common: { name: "Left/right wind angle (0–100)", type: "number", role: "level", read: true, write: true, min: 0, max: 100, def: 0 } },
{ id: "windUdAngle", common: { name: "Up/down wind angle (0–100)", type: "number", role: "level", read: true, write: true, min: 0, max: 100, def: 0 } },
{ id: "toggleDisplay", common: { name: "Toggle indoor unit display", type: "boolean", role: "button", read: false, write: true, def: false } },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const DEHUMIDIFIER_CONTROLS = [
{ id: "powerOn", common: { name: "Power on/off", type: "boolean", role: "switch.power", read: true, write: true, def: false } },
{ id: "mode", common: { name: "Operating mode", type: "string", role: "level.mode.dehumidifier", read: true, write: true, def: "set", states: { set: "Set", continuity: "Continuity", auto: "Auto", dry_clothes: "Dry clothes", dry_shoes: "Dry shoes", fan: "Fan" } } },
{ id: "targetHumidity", common: { name: "Target humidity", type: "number", role: "level.humidity", unit: "%", read: true, write: true, min: 0, max: 100, def: 50 } },
{ id: "fanSpeed", common: { name: "Fan speed (numeric)", type: "number", role: "level.fan", read: true, write: true, min: 0, max: 127, def: 40 } },
{ id: "fanSpeedName", common: { name: "Fan speed (named)", type: "string", role: "level.mode.fan", read: true, write: true, def: "LOW", states: { SILENT: "Silent", LOW: "Low", MEDIUM: "Medium", HIGH: "High", AUTO: "Auto" } } },
{ id: "ionMode", common: { name: "Ion / anion mode", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "sleepMode", common: { name: "Sleep mode", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "pumpSwitch", common: { name: "Drain pump", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "verticalSwing", common: { name: "Vertical swing", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "tankWarningLevel", common: { name: "Tank warning level", type: "number", role: "level", unit: "%", read: true, write: true, min: 0, max: 100, def: 100 } },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const FAN_CONTROLS = [
{ id: "powerOn", common: { name: "Power on/off", type: "boolean", role: "switch.power", read: true, write: true, def: false } },
{ id: "childLock", common: { name: "Child lock", type: "boolean", role: "switch.lock", read: true, write: true, def: false } },
{ id: "mode", common: { name: "Operating mode", type: "string", role: "level.mode.fan", read: true, write: true, def: "normal", states: { normal: "Normal", natural: "Natural", sleep: "Sleep", comfort: "Comfort", silent: "Silent", baby: "Baby", induction: "Induction", circulation: "Circulation", strong: "Strong", soft: "Soft", customize: "Customize", warm: "Warm", smart: "Smart" } } },
{ id: "fanSpeed", common: { name: "Fan speed", type: "number", role: "level.fan", read: true, write: true, min: 1, max: 26, def: 1 } },
{ id: "oscillate", common: { name: "Oscillation", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "oscillationMode", common: { name: "Oscillation mode", type: "string", role: "level.mode.swing", read: true, write: true, def: "off", states: { off: "Off", oscillation: "Oscillation", tilting: "Tilting", "curve-w": "Curve-W", "curve-8": "Curve-8", reserved: "Reserved", both: "Both" } } },
{ id: "oscillationAngle", common: { name: "Oscillation angle (deg)", type: "string", role: "level", read: true, write: true, def: "off", states: { off: "Off", 30: "30°", 60: "60°", 90: "90°", 120: "120°", 180: "180°", 360: "360°" } } },
{ id: "tiltingAngle", common: { name: "Tilting angle (deg)", type: "string", role: "level", read: true, write: true, def: "off", states: { off: "Off", 30: "30°", 60: "60°", 90: "90°", 120: "120°", 180: "180°", 360: "360°", "+60": "+60°", "-60": "-60°", 40: "40°" } } },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const PURIFIER_CONTROLS = [
{ id: "powerOn", common: { name: "Power on/off", type: "boolean", role: "switch.power", read: true, write: true, def: false } },
{ id: "mode", common: { name: "Operating mode", type: "string", role: "level.mode.purifier", read: true, write: true, def: "auto", states: { standby: "Standby", auto: "Auto", manual: "Manual", sleep: "Sleep", fast: "Fast", smoke: "Smoke" } } },
{ id: "fanSpeedName", common: { name: "Fan speed", type: "string", role: "level.mode.fan", read: true, write: true, def: "AUTO", states: { AUTO: "Auto", STANDBY: "Standby", LOW: "Low", MEDIUM: "Medium", HIGH: "High" } } },
{ id: "anion", common: { name: "Anion / ionizer", type: "boolean", role: "switch", read: true, write: true, def: false } },
{ id: "childLock", common: { name: "Child lock", type: "boolean", role: "switch.lock", read: true, write: true, def: false } },
{ id: "screenDisplayName", common: { name: "Screen display", type: "string", role: "state", read: true, write: true, def: "bright", states: { bright: "Bright", dim: "Dim", off: "Off" } } },
{ id: "detectMode", common: { name: "Detect mode", type: "string", role: "state", read: true, write: true, def: "off", states: { off: "Off", pm25: "PM2.5", methanal: "Methanal" } } },
{ id: "standby", common: { name: "Standby (auto-stop on clean air)", type: "boolean", role: "switch", read: true, write: true, def: false } },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const HUMIDIFIER_CONTROLS = [
{ id: "powerOn", common: { name: "Power on/off", type: "boolean", role: "switch.power", read: true, write: true, def: false } },
{ id: "mode", common: { name: "Operating mode", type: "string", role: "level.mode.humidifier", read: true, write: true, def: "manual", states: { manual: "Manual", auto: "Auto", continuous: "Continuous", "living-room": "Living room", "bed-room": "Bed room", kitchen: "Kitchen", sleep: "Sleep" } } },
{ id: "targetHumidity", common: { name: "Target humidity", type: "number", role: "level.humidity", unit: "%", read: true, write: true, min: 0, max: 100, def: 50 } },
{ id: "fanSpeedName", common: { name: "Fan speed", type: "string", role: "level.mode.fan", read: true, write: true, def: "LOW", states: { LOWEST: "Lowest", LOW: "Low", MEDIUM: "Medium", HIGH: "High", AUTO: "Auto", OFF: "Off" } } },
{ id: "screenDisplayName", common: { name: "Screen display", type: "string", role: "state", read: true, write: true, def: "bright", states: { bright: "Bright", dim: "Dim", off: "Off" } } },
{ id: "disinfect", common: { name: "Disinfect", type: "boolean", role: "switch", read: true, write: true, def: false } },
];
/** @returns {ioBroker.StateCommon} */
const onOff = (name) => ({ name, type: "boolean", role: "switch", read: true, write: true, def: false });
/** @returns {ioBroker.StateCommon} */
const power = () => ({ name: "Power on/off", type: "boolean", role: "switch.power", read: true, write: true, def: false });
/** @returns {ioBroker.StateCommon} */
const numLevel = (name, min, max, def, unit) => ({ name, type: "number", role: "level", read: true, write: true, min, max, def, ...(unit ? { unit } : {}) });
/** @returns {ioBroker.StateCommon} */
const numTemp = (name, min, max, def) => ({ name, type: "number", role: "level.temperature", unit: "°C", read: true, write: true, min, max, def });
/** @returns {ioBroker.StateCommon} */
const enumState = (name, states, def) => ({ name, type: "string", role: "state", read: true, write: true, def, states });
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const FRESH_AIR_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "fanSpeed", common: numLevel("Fan speed", 0, 100, 40) },
{ id: "linkToAc", common: onOff("Link to AC") },
{ id: "sleepMode", common: onOff("Sleep mode") },
{ id: "ecoMode", common: onOff("Eco mode") },
{ id: "auxHeating", common: onOff("Aux heating") },
{ id: "powerfulPurify", common: onOff("Powerful purify") },
{ id: "scheduled", common: onOff("Scheduled") },
{ id: "childLock", common: onOff("Child lock") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const HEATPUMP_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "mode", common: enumState("Mode", { off: "off", auto: "auto", cool: "cool", heat: "heat" }, "auto") },
{ id: "targetTemperature", common: numTemp("Target temperature", 5, 60, 25) },
{ id: "auxHeating", common: onOff("Aux heating") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const HEAT_PUMP_WATER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "mode", common: enumState("Mode", { off: "off", energy: "energy", standard: "standard", hot: "hot", smart: "smart", vacation: "vacation" }, "standard") },
{ id: "targetTemperature", common: numTemp("Target temperature", 30, 75, 50) },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const HEAT_PUMP_CTRL_CONTROLS = [
{ id: "zone1Power", common: onOff("Zone 1 power") },
{ id: "zone2Power", common: onOff("Zone 2 power") },
{ id: "dhwPower", common: onOff("DHW power") },
{ id: "zone1Curve", common: onOff("Zone 1 climate curve") },
{ id: "zone2Curve", common: onOff("Zone 2 climate curve") },
{ id: "tbh", common: onOff("Tank booster heater (TBH)") },
{ id: "fastDhw", common: onOff("Fast DHW") },
{ id: "mode", common: numLevel("Mode (raw 1..5)", 1, 5, 2) },
{ id: "zone1TargetTemp", common: numTemp("Zone 1 target temperature", 5, 60, 25) },
{ id: "zone2TargetTemp", common: numTemp("Zone 2 target temperature", 5, 60, 25) },
{ id: "dhwTargetTemp", common: numTemp("DHW target temperature", 30, 75, 45) },
{ id: "roomTargetTemp", common: numTemp("Room target temperature", 5, 35, 22) },
{ id: "silentMode", common: onOff("Silent mode") },
{ id: "silentLevel", common: enumState("Silent level", { off: "off", silent: "silent", super_silent: "super_silent" }, "off") },
{ id: "ecoMode", common: onOff("Eco mode") },
{ id: "disinfect", common: onOff("Disinfect") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const WASHER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "start", common: onOff("Start / pause") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const ELECTRIC_HEATER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "mode", common: numLevel("Mode (raw)", 0, 5, 0) },
{ id: "heatingLevel", common: numLevel("Heating level", 0, 10, 0) },
{ id: "targetTemperature", common: numTemp("Target temperature", 5, 35, 22) },
{ id: "childLock", common: onOff("Child lock") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const GAS_BOILER_CONTROLS = [
{ id: "mainPower", common: power() },
{ id: "heatingPower", common: onOff("Heating power") },
{ id: "heatingTemperature", common: numTemp("Heating temperature", 30, 80, 60) },
{ id: "bathingTemperature", common: numTemp("Bathing temperature", 35, 60, 45) },
{ id: "coldWaterSingle", common: onOff("Cold water single") },
{ id: "coldWaterDot", common: onOff("Cold water dot") },
{ id: "heatingMode", common: enumState("Heating mode", { normal_mode: "normal_mode", out_mode: "out_mode", home_mode: "home_mode", sleep_mode: "sleep_mode" }, "normal_mode") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const GAS_WATER_HEATER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "targetTemperature", common: numTemp("Target temperature", 35, 75, 45) },
{ id: "zeroColdWater", common: onOff("Zero cold water") },
{ id: "zeroColdPulse", common: onOff("Zero cold pulse") },
{ id: "smartVolume", common: onOff("Smart volume") },
{ id: "protection", common: onOff("Protection") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const ELECTRIC_WATER_HEATER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "targetTemperature", common: numTemp("Target temperature", 30, 75, 50) },
{ id: "wholeTankHeating", common: onOff("Whole tank heating") },
{ id: "variableHeating", common: onOff("Variable heating") },
{ id: "protection", common: onOff("Protection") },
{ id: "memory", common: onOff("Memory boost (Memo U)") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const DISHWASHER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "mode", common: numLevel("Mode (raw)", 0, 20, 0) },
{ id: "work", common: numLevel("Work command (raw)", 0, 8, 3) },
{ id: "childLock", common: onOff("Child lock") },
{ id: "storage", common: onOff("Storage mode") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const MICROWAVE_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "childLock", common: onOff("Child lock") },
{ id: "workMode", common: numLevel("Work mode (raw)", 0, 30, 0) },
{ id: "workTime", common: numLevel("Work time (s)", 0, 86400, 60, "s") },
{ id: "temperature", common: numTemp("Temperature", 0, 250, 0) },
{ id: "firePower", common: numLevel("Fire power", 0, 100, 0) },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const INTEGRATED_OVEN_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "childLock", common: onOff("Child lock") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const RANGE_HOOD_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "fanLevel", common: numLevel("Fan level", 0, 4, 0) },
{ id: "light", common: { name: "Light", type: "boolean", role: "switch.light", read: true, write: true, def: false } },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const VACUUM_CONTROLS = [
{ id: "workMode", common: enumState("Work mode", { charge: "charge", work: "work", stop: "stop", pause: "pause" }, "stop") },
{ id: "cleanMode", common: numLevel("Clean mode", 0, 10, 2) },
{ id: "fanLevel", common: numLevel("Fan level", 0, 5, 2) },
{ id: "waterLevel", common: numLevel("Water level", 0, 5, 1) },
{ id: "voiceVolume", common: numLevel("Voice volume", 0, 10, 0) },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const SMART_TOILET_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "childLock", common: onOff("Child lock") },
{ id: "sensorLight", common: onOff("Sensor light") },
{ id: "foamShield", common: onOff("Foam shield") },
{ id: "dryLevel", common: numLevel("Dry level", 0, 3, 0) },
{ id: "seatTempLevel", common: numLevel("Seat temperature level", 0, 7, 0) },
{ id: "waterTempLevel", common: numLevel("Water temperature level", 0, 7, 0) },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const WATER_PURIFIER_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "childLock", common: onOff("Child lock") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const LIGHT_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "brightness", common: { name: "Brightness", type: "number", role: "level.dimmer", read: true, write: true, min: 0, max: 255, def: 128 } },
{ id: "colorTemperature", common: { name: "Color temperature", type: "number", role: "level.color.temperature", read: true, write: true, min: 0, max: 255, def: 128 } },
{ id: "effect", common: numLevel("Effect (1..5)", 1, 5, 1) },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const BATHROOM_HEATER_CONTROLS = [
{ id: "mainLight", common: { name: "Main light", type: "boolean", role: "switch.light", read: true, write: true, def: false } },
{ id: "nightLight", common: { name: "Night light", type: "boolean", role: "switch.light", read: true, write: true, def: false } },
{ id: "mode", common: enumState("Mode", { 0: "off", 1: "heat_high", 2: "heat_low", 3: "bath", 4: "blow", 5: "ventilation", 6: "dry" }, "0") },
{ id: "direction", common: numLevel("Direction (0xFD = oscillate)", 0, 255, 253) },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const DISHWASHER_X34_CONTROLS = [
{ id: "powerOn", common: power() },
{ id: "childLock", common: onOff("Child lock") },
];
/** @type {Array<{id: string, common: ioBroker.StateCommon}>} */
const BATHROOM_FAN_CONTROLS = [
{ id: "light", common: { name: "Light", type: "boolean", role: "switch.light", read: true, write: true, def: false } },
{ id: "fanSpeed", common: numLevel("Fan speed (0..2)", 0, 2, 0) },
{ id: "ventilation", common: onOff("Ventilation") },
{ id: "smellySensor", common: onOff("Smelly sensor") },
];
const APPLIANCE = midea.APPLIANCE_TYPE;
const TYPED_CONTROLS = {
[APPLIANCE.AC]: AC_CONTROLS,
[APPLIANCE.COMMERCIAL_AC]: AC_CONTROLS,
[APPLIANCE.DEHUMIDIFIER]: DEHUMIDIFIER_CONTROLS,
[APPLIANCE.FAN]: FAN_CONTROLS,
[APPLIANCE.PURIFIER]: PURIFIER_CONTROLS,
[APPLIANCE.HUMIDIFIER]: HUMIDIFIER_CONTROLS,
[APPLIANCE.FRESH_AIR]: FRESH_AIR_CONTROLS,
[APPLIANCE.HEATPUMP]: HEATPUMP_CONTROLS,
[APPLIANCE.HEAT_PUMP_WATER]: HEAT_PUMP_WATER_CONTROLS,
[APPLIANCE.HEAT_PUMP_CONTROLLER]: HEAT_PUMP_CTRL_CONTROLS,
[APPLIANCE.TOP_LOAD_WASHER]: WASHER_CONTROLS,
[APPLIANCE.FRONT_LOAD_WASHER]: WASHER_CONTROLS,
[APPLIANCE.DRYER]: WASHER_CONTROLS,
[APPLIANCE.ELECTRIC_HEATER]: ELECTRIC_HEATER_CONTROLS,
[APPLIANCE.GAS_BOILER]: GAS_BOILER_CONTROLS,
[APPLIANCE.GAS_WATER_HEATER]: GAS_WATER_HEATER_CONTROLS,
[APPLIANCE.ELECTRIC_WATER_HEATER]: ELECTRIC_WATER_HEATER_CONTROLS,
[APPLIANCE.DISHWASHER]: DISHWASHER_CONTROLS,
[APPLIANCE.MICROWAVE]: MICROWAVE_CONTROLS,
[APPLIANCE.INTEGRATED_OVEN]: INTEGRATED_OVEN_CONTROLS,
[APPLIANCE.RANGE_HOOD]: RANGE_HOOD_CONTROLS,
[APPLIANCE.VACUUM]: VACUUM_CONTROLS,
[APPLIANCE.SMART_TOILET]: SMART_TOILET_CONTROLS,
[APPLIANCE.WATER_PURIFIER]: WATER_PURIFIER_CONTROLS,
[APPLIANCE.LIGHT]: LIGHT_CONTROLS,
[APPLIANCE.BATHROOM_HEATER]: BATHROOM_HEATER_CONTROLS,
[APPLIANCE.DISHWASHER_X34]: DISHWASHER_X34_CONTROLS,
[APPLIANCE.BATHROOM_FAN]: BATHROOM_FAN_CONTROLS,
};
class MideaAdapter extends utils.Adapter {
constructor(options) {
super({ ...options, name: "midea" });
/** @type {Map<string, any>} */
this.devices = new Map();
/** @type {Map<string, any>} */
this.descriptors = new Map();
/**
* Cloud-listed appliances keyed by id. Populated on each discovery
* cycle so onStateChange can produce an actionable warning when the
* user writes to a control whose device is not currently registered.
* @type {Map<string, {name?: string, type?: number, online?: boolean, modelNumber?: string}>}
*/
this.cloudAppliances = new Map();
/**
* Last LAN-discovered host per device id. Populated on every
* runDiscoveryCycle() and consulted by onMessage("refreshDeviceList")
* so the admin form can merge live LAN data into the device table.
* @type {Map<string, string>}
*/
this.lastLanHosts = new Map();
/**
* Serialises midea.discover() calls. The discovery cycle and the
* admin "Refresh devices" handler both probe the LAN; running them
* concurrently leaves device replies arriving on whichever UDP
* socket happens to win the race, so each side ends up with an
* incomplete list. We chain new calls onto this promise so they
* run back to back instead of in parallel.
* @type {Promise<any>}
*/
this.discoverChain = Promise.resolve();
/** @type {midea.CloudClient|midea.CloudClientV1|null} */
this.cloud = null;
this.pollTimer = null;
this.shuttingDown = false;
/**
* Buffer of pending deviceList row updates keyed by device id.
* Each `_persistDeviceCredentials` call merges into this map and
* (re)arms a 1 s flush timer. ioBroker reloads the adapter on every
* native-config write, so coalescing the field-by-field updates that
* arrive across discovery / handshake / cloud-listing into one write
* collapses the onboarding restart storm to a single reload.
* @type {Map<string, {id: string, name?: string, host?: string, token?: string|null, key?: string|null}>}
*/
this._pendingDeviceListUpdates = new Map();
/** @type {NodeJS.Timeout|null} */
this._pendingDeviceListTimer = null;
this.json2iob = new Json2iob(this);
this.pollIntervalMs = 30 * 1000;
this.on("ready", this.onReady.bind(this));
this.on("stateChange", this.onStateChange.bind(this));
this.on("message", this.onMessage.bind(this));
this.on("unload", this.onUnload.bind(this));
}
async onReady() {
await this.deleteLegacyTree();
await this.deleteOrphanControls();
await this.deleteEmptyCapabilities();
await this.setStateAsync("info.connection", false, true);
if (!this.config.user || !this.config.password) {
this.log.error("Midea cloud credentials missing — please configure user and password in adapter settings.");
return;
}
const intervalSec = Math.max(5, Math.min(3600, Number(this.config.interval) || 30));
this.pollIntervalMs = intervalSec * 1000;
this.log.debug(`Midea adapter starting up, poll interval=${intervalSec} s`);
this.cloud = midea.createCloudClient({
app: this.config.cloudApp || "msmarthome",
user: this.config.user,
password: this.config.password,
logger: this.log,
});
try {
await this.runDiscoveryCycle();
} catch (err) {
this.log.error(`Initial discovery failed: ${errMessage(err)}`);
}
await this.subscribeStatesAsync("*.control.*");
this.schedulePoll();
}
/**
* Remove control-channel states whose IDs are no longer part of the
* current TYPED_CONTROLS definition for the device type. Cleans up
* renamed states from v1.x upgrades (e.g. operationalMode -> mode).
*/
async deleteOrphanControls() {
const all = await this.getAdapterObjectsAsync();
const ns = `${this.namespace}.`;
// Build applianceType map from stored info states (descriptors not yet
// populated at startup — this runs before runDiscoveryCycle).
const appTypeByDevice = new Map();
for (const [fullId, obj] of Object.entries(all)) {
if (!fullId.startsWith(ns)) continue;
const rel = fullId.slice(ns.length);
// Match "<deviceId>.info.applianceType" state
if (!/^[^.]+\.info\.applianceType$/.test(rel)) continue;
if (obj.type !== "state") continue;
const deviceId = rel.split(".")[0];
const st = await this.getStateAsync(rel);
if (st && st.val != null) appTypeByDevice.set(deviceId, Number(st.val));
}
let removed = 0;
for (const [fullId, obj] of Object.entries(all)) {
if (!fullId.startsWith(ns)) continue;
const rel = fullId.slice(ns.length);
const parts = rel.split(".");
if (parts.length !== 3 || parts[1] !== "control") continue;
if (obj.type !== "state") continue;
const deviceId = parts[0];
const controlId = parts[2];
const appType = appTypeByDevice.get(deviceId);
if (appType == null) continue;
const defs = TYPED_CONTROLS[appType];
if (!defs) continue;
if (defs.find((d) => d.id === controlId)) continue;
try {
await this.delObjectAsync(rel);
this.log.info(`deleteOrphanControls: removed obsolete ${rel}`);
removed++;
} catch (err) {
this.log.warn(`deleteOrphanControls: could not delete ${rel}: ${errMessage(err)}`);
}
}
if (removed > 0) this.log.info(`deleteOrphanControls: removed ${removed} obsolete control object(s)`);
}
/**
* Remove `<deviceId>.capabilities` channels that have no state objects
* underneath. Pre-existing installs created the empty channel for every
* device in createDeviceShell; we now create it lazily in
* publishCapabilities, so the pre-existing empty channels can go.
*/
async deleteEmptyCapabilities() {
const all = await this.getAdapterObjectsAsync();
const ns = `${this.namespace}.`;
const capChannels = new Set();
const capStateParents = new Set();
for (const fullId of Object.keys(all)) {
if (!fullId.startsWith(ns)) continue;
const rel = fullId.slice(ns.length);
const parts = rel.split(".");
if (parts.length === 2 && parts[1] === "capabilities" && all[fullId].type === "channel") {
capChannels.add(rel);
} else if (parts.length >= 3 && parts[1] === "capabilities" && all[fullId].type === "state") {
capStateParents.add(`${parts[0]}.capabilities`);
}
}
let removed = 0;
for (const rel of capChannels) {
if (capStateParents.has(rel)) continue;
try {
await this.delObjectAsync(rel);
removed++;
} catch (err) {
this.log.warn(`deleteEmptyCapabilities: could not delete ${rel}: ${errMessage(err)}`);
}
}
if (removed > 0) this.log.info(`deleteEmptyCapabilities: removed ${removed} empty capabilities channel(s)`);
}
/**
* One-shot cleanup of the pre-1.4.0 object tree. The 1.4.0 layout drops
* the `devices.<id>` prefix and renames `controls` to `control`, so any
* leftover state from older versions would just sit there as orphans.
* We delete every top-level object under the instance and recreate the
* `info` channel from scratch so runDiscoveryCycle() builds the new
* layout cleanly.
*/
async deleteLegacyTree() {
const flag = await this.getStateAsync("info.migrationV1");
if (flag && flag.val === true) return;
const all = await this.getAdapterObjectsAsync();
const ns = `${this.namespace}.`;
const topLevel = new Set();
let hasLegacy = false;
for (const fullId of Object.keys(all)) {
if (!fullId.startsWith(ns)) continue;
const top = fullId.slice(ns.length).split(".")[0];
if (!top) continue;
topLevel.add(top);
// Pre-1.4.0 layout had a top-level `devices` channel containing
// every appliance. Anything else (`info`, the new top-level device
// ids) is current. Without that marker we're a fresh install and
// skip the cleanup entirely.
if (top === "devices") hasLegacy = true;
}
if (!hasLegacy) {
await this.setStateAsync("info.migrationV1", true, true);
return;
}
this.log.info("Clearing pre-1.4.0 object tree");
for (const top of topLevel) {
try {
await this.delObjectAsync(top, { recursive: true });
} catch (err) {
this.log.warn(`Could not delete ${top}: ${errMessage(err)}`);
}
}
await this.setObjectNotExistsAsync("info", {
type: "channel",
common: { name: "Information" },
native: {},
});
await this.setObjectNotExistsAsync("info.connection", {
type: "state",
common: {
role: "indicator.connected",
name: "Device or service connected",
type: "boolean",
read: true,
write: false,
def: false,
},
native: {},
});
await this.setObjectNotExistsAsync("info.migrationV1", {
type: "state",
common: {
role: "indicator",
name: "Legacy state cleanup completed",
type: "boolean",
read: true,
write: false,
def: false,
},
native: {},
});
await this.setStateAsync("info.connection", false, true);
await this.setStateAsync("info.migrationV1", true, true);
this.log.info(`Cleanup complete (${topLevel.size} top-level item(s) cleared)`);
}
/**
* Run a midea.discover() call serialised against any other discover
* already in flight on this adapter instance. Avoids the UDP-socket
* race between runDiscoveryCycle and the refreshDeviceList handler.
*
* @param {object} opts
*/
async serialDiscover(opts) {
const next = this.discoverChain.then(
() => midea.discover(opts),
() => midea.discover(opts), // ignore prior failure, still run ours
);
// Hold the chain on `next` (swallowing rejections) so the chain
// never short-circuits on a failure.
this.discoverChain = next.catch(() => undefined);
return next;
}
schedulePoll() {
if (this.shuttingDown) return;
this.pollTimer = setTimeout(() => {
this.pollAllDevices()
.catch((err) => this.log.warn(`Polling cycle failed: ${errMessage(err)}`))
.finally(() => this.schedulePoll());
}, this.pollIntervalMs);
}
async runDiscoveryCycle() {
const cloud = this.cloud;
const cloudByIdName = new Map();
let cloudList = null;
if (cloud) {
try {
cloudList = await cloud.listAppliances();
await this.setStateAsync("info.connection", true, true);
this.cloudAppliances.clear();
for (const item of cloudList) {
if (item.name) cloudByIdName.set(item.id, item.name);
this.cloudAppliances.set(item.id, {
name: item.name,
type: item.type,
online: item.online,
modelNumber: item.modelNumber,
});
}
this.log.info(`Cloud listing: ${cloudList.length} appliance(s)`);
for (const item of cloudList) {
const typeHex = `0x${Number(item.type || 0).toString(16)}`;
this.log.debug(` cloud: id=${item.id} name="${item.name || ""}" type=${typeHex} online=${item.online}`);
}
} catch (err) {
this.log.warn(`Cloud listAppliances failed: ${errMessage(err)}`);
this.log.info(`Please check if you have a correct MSmartHome App account or register a new account`);
await this.setStateAsync("info.connection", false, true);
}
}
let broadcastTargets = [];
try { broadcastTargets = midea.enumerateBroadcastTargets(); } catch (_e) { /* swallow */ }
this.log.debug(`LAN discovery: broadcasting to [${broadcastTargets.join(", ")}] on UDP/6445+20086`);
const deviceListCfg = /** @type {Array<{id?: string, name?: string, host?: string, token?: string, key?: string}>} */ (
Array.isArray(this.config.deviceList) ? this.config.deviceList : []
);
const staticIps = [];
for (const entry of deviceListCfg) {
const host = String((entry && entry.host) || "").trim();
if (host) staticIps.push(host);
}
if (staticIps.length) {
this.log.info(`LAN discovery: also unicast-probing configured device IPs [${staticIps.join(", ")}]`);
}
const discoveryTargets = [...new Set([...broadcastTargets, ...staticIps])];
const lanDevices = await this.serialDiscover({ targets: discoveryTargets, logger: this.log });
// Upsert only — a 0-result blip should not wipe IPs we learned
// earlier and that the admin refresh handler relies on.
for (const desc of lanDevices) {
if (desc.id && desc.host) this.lastLanHosts.set(String(desc.id), String(desc.host));
}
if (lanDevices.length === 0) {
this.log.warn(
"LAN discovery found 0 appliance(s) — your ioBroker host is not on the same broadcast domain as the appliance, or UDP 6445 is firewalled. Across VLANs you need a UDP broadcast relay (e.g. udpbroadcastrelay).",
);
} else {
this.log.info(`LAN discovery found ${lanDevices.length} appliance(s)`);
}
for (const desc of lanDevices) {
const typeHex = `0x${Number(desc.applianceType || 0).toString(16)}`;
this.log.debug(` lan: id=${desc.id} host=${desc.host} port=${desc.port} type=${typeHex} (${desc.applianceTypeName}) protocol=${desc.protocol}`);
}
for (const desc of lanDevices) {
const cloudName = cloudByIdName.get(desc.id);
if (cloudName) desc.name = cloudName;
// The cloud listing carries the 8-digit model number that LAN
// discovery never reports. Some AC decoders (e.g. the 0x7e
// new-protocol temperature path) are gated on a specific model,
// so pass it through when we have it.
const cloudInfo = this.cloudAppliances.get(desc.id);
if (cloudInfo && cloudInfo.modelNumber) desc.modelNumber = cloudInfo.modelNumber;
try {
await this.registerDevice(desc);
} catch (err) {
this.log.warn(`Could not initialise device ${desc.id}: ${errMessage(err)}`);
}
}
if (cloudList) {
for (const item of cloudList) {
if (this.descriptors.has(item.id)) continue;
// Manual IP override: the user typed a host into the
// deviceList admin row, so UDP discovery is irrelevant —
// skip the broadcast-domain warning and try TCP/6444
// directly. V3 firmware is assumed (MSmartHome / Midea
// Air / NetHome Plus all list V3 appliances; V1/V2 paths
// run cloudless and shouldn't reach this branch).
const manualRow = deviceListCfg.find((r) => r && String(r.id || "") === String(item.id));
const manualHost = manualRow && typeof manualRow.host === "string" ? manualRow.host.trim() : "";
if (manualHost) {