-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
homeassistant.ts
2290 lines (2063 loc) · 110 KB
/
homeassistant.ts
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
import assert from 'assert';
import bind from 'bind-decorator';
import stringify from 'json-stable-stringify-without-jsonify';
import * as zhc from 'zigbee-herdsman-converters';
import logger from '../util/logger';
import * as settings from '../util/settings';
import utils, {assertBinaryExpose, assertEnumExpose, assertNumericExpose, isBinaryExpose, isEnumExpose, isNumericExpose} from '../util/utils';
import Extension from './extension';
interface MockProperty {
property: string;
value: KeyValue | string | null;
}
interface DiscoveryEntry {
mockProperties: MockProperty[];
type: string;
object_id: string;
discovery_payload: KeyValue;
}
interface Discovered {
mockProperties: Set<MockProperty>;
messages: {[s: string]: {payload: string; published: boolean}};
triggers: Set<string>;
discovered: boolean;
}
interface ActionData {
action: string;
button?: string;
scene?: string;
region?: string;
}
const ACTION_PATTERNS: string[] = [
'^(?<button>(?:button_)?[a-z0-9]+)_(?<action>(?:press|hold)(?:_release)?)$',
'^(?<action>recall|scene)_(?<scene>[0-2][0-9]{0,2})$',
'^(?<actionPrefix>region_)(?<region>[1-9]|10)_(?<action>enter|leave|occupied|unoccupied)$',
'^(?<action>dial_rotate)_(?<direction>left|right)_(?<speed>step|slow|fast)$',
'^(?<action>brightness_step)(?:_(?<direction>up|down))?$',
];
const SENSOR_CLICK: Readonly<DiscoveryEntry> = {
type: 'sensor',
object_id: 'click',
mockProperties: [{property: 'click', value: null}],
discovery_payload: {
name: 'Click',
icon: 'mdi:toggle-switch',
value_template: '{{ value_json.click }}',
},
};
const ACCESS_STATE = 0b001;
const ACCESS_SET = 0b010;
const GROUP_SUPPORTED_TYPES: ReadonlyArray<string> = ['light', 'switch', 'lock', 'cover'];
const DEFAULT_STATUS_TOPIC = 'homeassistant/status';
const COVER_OPENING_LOOKUP: ReadonlyArray<string> = ['opening', 'open', 'forward', 'up', 'rising'];
const COVER_CLOSING_LOOKUP: ReadonlyArray<string> = ['closing', 'close', 'backward', 'back', 'reverse', 'down', 'declining'];
const COVER_STOPPED_LOOKUP: ReadonlyArray<string> = ['stopped', 'stop', 'pause', 'paused'];
const SWITCH_DIFFERENT: ReadonlyArray<string> = ['valve_detection', 'window_detection', 'auto_lock', 'away_mode'];
const LEGACY_MAPPING: ReadonlyArray<{models: string[]; discovery: DiscoveryEntry}> = [
{
models: [
'WXKG01LM',
'HS1EB/HS1EB-E',
'ICZB-KPD14S',
'TERNCY-SD01',
'TERNCY-PP01',
'ICZB-KPD18S',
'E1766',
'ZWallRemote0',
'ptvo.switch',
'2AJZ4KPKEY',
'ZGRC-KEY-013',
'HGZB-02S',
'HGZB-045',
'HGZB-1S',
'AV2010/34',
'IM6001-BTP01',
'WXKG11LM',
'WXKG03LM',
'WXKG02LM_rev1',
'WXKG02LM_rev2',
'QBKG04LM',
'QBKG03LM',
'QBKG11LM',
'QBKG21LM',
'QBKG22LM',
'WXKG12LM',
'QBKG12LM',
'E1743',
],
discovery: SENSOR_CLICK,
},
{
models: ['ICTC-G-1'],
discovery: {
type: 'sensor',
mockProperties: [{property: 'brightness', value: null}],
object_id: 'brightness',
discovery_payload: {
name: 'Brightness',
unit_of_measurement: 'brightness',
icon: 'mdi:brightness-5',
value_template: '{{ value_json.brightness }}',
},
},
},
];
const BINARY_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
activity_led_indicator: {icon: 'mdi:led-on'},
auto_off: {icon: 'mdi:flash-auto'},
battery_low: {entity_category: 'diagnostic', device_class: 'battery'},
button_lock: {entity_category: 'config', icon: 'mdi:lock'},
calibration: {entity_category: 'config', icon: 'mdi:progress-wrench'},
capabilities_configurable_curve: {entity_category: 'diagnostic', icon: 'mdi:tune'},
capabilities_forward_phase_control: {entity_category: 'diagnostic', icon: 'mdi:tune'},
capabilities_overload_detection: {entity_category: 'diagnostic', icon: 'mdi:tune'},
capabilities_reactance_discriminator: {entity_category: 'diagnostic', icon: 'mdi:tune'},
capabilities_reverse_phase_control: {entity_category: 'diagnostic', icon: 'mdi:tune'},
carbon_monoxide: {device_class: 'carbon_monoxide'},
card: {entity_category: 'config', icon: 'mdi:clipboard-check'},
child_lock: {entity_category: 'config', icon: 'mdi:account-lock'},
color_sync: {entity_category: 'config', icon: 'mdi:sync-circle'},
consumer_connected: {device_class: 'plug'},
contact: {device_class: 'door'},
garage_door_contact: {device_class: 'garage_door', payload_on: false, payload_off: true},
eco_mode: {entity_category: 'config', icon: 'mdi:leaf'},
expose_pin: {entity_category: 'config', icon: 'mdi:pin'},
flip_indicator_light: {entity_category: 'config', icon: 'mdi:arrow-left-right'},
gas: {device_class: 'gas'},
indicator_mode: {entity_category: 'config', icon: 'mdi:led-on'},
invert_cover: {entity_category: 'config', icon: 'mdi:arrow-left-right'},
led_disabled_night: {entity_category: 'config', icon: 'mdi:led-off'},
led_indication: {entity_category: 'config', icon: 'mdi:led-on'},
led_enable: {entity_category: 'config', icon: 'mdi:led-on'},
legacy: {entity_category: 'config', icon: 'mdi:cog'},
motor_reversal: {entity_category: 'config', icon: 'mdi:arrow-left-right'},
moving: {device_class: 'moving'},
no_position_support: {entity_category: 'config', icon: 'mdi:minus-circle-outline'},
noise_detected: {device_class: 'sound'},
occupancy: {device_class: 'occupancy'},
power_outage_memory: {entity_category: 'config', icon: 'mdi:memory'},
presence: {device_class: 'presence'},
setup: {device_class: 'running'},
smoke: {device_class: 'smoke'},
sos: {device_class: 'safety'},
schedule: {icon: 'mdi:calendar'},
status_capacitive_load: {entity_category: 'diagnostic', icon: 'mdi:tune'},
status_forward_phase_control: {entity_category: 'diagnostic', icon: 'mdi:tune'},
status_inductive_load: {entity_category: 'diagnostic', icon: 'mdi:tune'},
status_overload: {entity_category: 'diagnostic', icon: 'mdi:tune'},
status_reverse_phase_control: {entity_category: 'diagnostic', icon: 'mdi:tune'},
tamper: {device_class: 'tamper'},
temperature_scale: {entity_category: 'config', icon: 'mdi:temperature-celsius'},
test: {entity_category: 'diagnostic', icon: 'mdi:test-tube'},
th_heater: {icon: 'mdi:heat-wave'},
trigger_indicator: {icon: 'mdi:led-on'},
valve_alarm: {device_class: 'problem'},
valve_detection: {icon: 'mdi:pipe-valve'},
valve_state: {device_class: 'opening'},
vibration: {device_class: 'vibration'},
water_leak: {device_class: 'moisture'},
window: {device_class: 'window'},
window_detection: {icon: 'mdi:window-open-variant'},
window_open: {device_class: 'window'},
} as const;
const NUMERIC_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
ac_frequency: {device_class: 'frequency', enabled_by_default: false, entity_category: 'diagnostic', state_class: 'measurement'},
action_duration: {icon: 'mdi:timer', device_class: 'duration'},
alarm_humidity_max: {device_class: 'humidity', entity_category: 'config', icon: 'mdi:water-plus'},
alarm_humidity_min: {device_class: 'humidity', entity_category: 'config', icon: 'mdi:water-minus'},
alarm_temperature_max: {device_class: 'temperature', entity_category: 'config', icon: 'mdi:thermometer-high'},
alarm_temperature_min: {device_class: 'temperature', entity_category: 'config', icon: 'mdi:thermometer-low'},
angle: {icon: 'angle-acute'},
angle_axis: {icon: 'angle-acute'},
aqi: {device_class: 'aqi', state_class: 'measurement'},
auto_relock_time: {entity_category: 'config', icon: 'mdi:timer'},
away_preset_days: {entity_category: 'config', icon: 'mdi:timer'},
away_preset_temperature: {entity_category: 'config', icon: 'mdi:thermometer'},
ballast_maximum_level: {entity_category: 'config'},
ballast_minimum_level: {entity_category: 'config'},
ballast_physical_maximum_level: {entity_category: 'diagnostic'},
ballast_physical_minimum_level: {entity_category: 'diagnostic'},
battery: {device_class: 'battery', state_class: 'measurement'},
battery2: {device_class: 'battery', entity_category: 'diagnostic', state_class: 'measurement'},
battery_voltage: {device_class: 'voltage', entity_category: 'diagnostic', state_class: 'measurement', enabled_by_default: true},
boost_heating_countdown: {device_class: 'duration'},
boost_heating_countdown_time_set: {entity_category: 'config', icon: 'mdi:timer'},
boost_time: {entity_category: 'config', icon: 'mdi:timer'},
calibration: {entity_category: 'config', icon: 'mdi:wrench-clock'},
calibration_time: {entity_category: 'config', icon: 'mdi:wrench-clock'},
co2: {device_class: 'carbon_dioxide', state_class: 'measurement'},
comfort_temperature: {entity_category: 'config', icon: 'mdi:thermometer'},
cpu_temperature: {
device_class: 'temperature',
entity_category: 'diagnostic',
state_class: 'measurement',
},
cube_side: {icon: 'mdi:cube'},
current: {
device_class: 'current',
enabled_by_default: false,
entity_category: 'diagnostic',
state_class: 'measurement',
},
current_phase_b: {
device_class: 'current',
enabled_by_default: false,
entity_category: 'diagnostic',
state_class: 'measurement',
},
current_phase_c: {
device_class: 'current',
enabled_by_default: false,
entity_category: 'diagnostic',
state_class: 'measurement',
},
deadzone_temperature: {entity_category: 'config', icon: 'mdi:thermometer'},
detection_interval: {icon: 'mdi:timer'},
device_temperature: {
device_class: 'temperature',
entity_category: 'diagnostic',
state_class: 'measurement',
},
distance: {device_class: 'distance', state_class: 'measurement'},
duration: {entity_category: 'config', icon: 'mdi:timer'},
eco2: {device_class: 'carbon_dioxide', state_class: 'measurement'},
eco_temperature: {entity_category: 'config', icon: 'mdi:thermometer'},
energy: {device_class: 'energy', state_class: 'total_increasing'},
external_temperature_input: {icon: 'mdi:thermometer'},
formaldehyd: {state_class: 'measurement'},
gas_density: {icon: 'mdi:google-circles-communities', state_class: 'measurement'},
hcho: {icon: 'mdi:air-filter', state_class: 'measurement'},
humidity: {device_class: 'humidity', state_class: 'measurement'},
humidity_calibration: {entity_category: 'config', icon: 'mdi:wrench-clock'},
humidity_max: {entity_category: 'config', icon: 'mdi:water-percent'},
humidity_min: {entity_category: 'config', icon: 'mdi:water-percent'},
illuminance_calibration: {entity_category: 'config', icon: 'mdi:wrench-clock'},
illuminance_lux: {device_class: 'illuminance', state_class: 'measurement'},
illuminance: {device_class: 'illuminance', enabled_by_default: false, state_class: 'measurement'},
linkquality: {
enabled_by_default: false,
entity_category: 'diagnostic',
icon: 'mdi:signal',
state_class: 'measurement',
},
local_temperature: {device_class: 'temperature', state_class: 'measurement'},
max_range: {entity_category: 'config', icon: 'mdi:signal-distance-variant'},
max_temperature: {entity_category: 'config', icon: 'mdi:thermometer-high'},
max_temperature_limit: {entity_category: 'config', icon: 'mdi:thermometer-high'},
min_temperature_limit: {entity_category: 'config', icon: 'mdi:thermometer-low'},
min_temperature: {entity_category: 'config', icon: 'mdi:thermometer-low'},
minimum_on_level: {entity_category: 'config'},
measurement_poll_interval: {entity_category: 'config', icon: 'mdi:clock-out'},
motion_sensitivity: {entity_category: 'config', icon: 'mdi:motion-sensor'},
noise: {device_class: 'sound_pressure', state_class: 'measurement'},
noise_detect_level: {icon: 'mdi:volume-equal'},
noise_timeout: {icon: 'mdi:timer'},
occupancy_level: {icon: 'mdi:motion-sensor'},
occupancy_sensitivity: {entity_category: 'config', icon: 'mdi:motion-sensor'},
occupancy_timeout: {entity_category: 'config', icon: 'mdi:timer'},
overload_protection: {icon: 'mdi:flash'},
pm10: {device_class: 'pm10', state_class: 'measurement'},
pm25: {device_class: 'pm25', state_class: 'measurement'},
people: {state_class: 'measurement', icon: 'mdi:account-multiple'},
position: {icon: 'mdi:valve', state_class: 'measurement'},
power: {device_class: 'power', state_class: 'measurement'},
power_phase_b: {device_class: 'power', state_class: 'measurement'},
power_phase_c: {device_class: 'power', state_class: 'measurement'},
power_factor: {device_class: 'power_factor', enabled_by_default: false, entity_category: 'diagnostic', state_class: 'measurement'},
power_outage_count: {icon: 'mdi:counter', enabled_by_default: false},
precision: {entity_category: 'config', icon: 'mdi:decimal-comma-increase'},
pressure: {device_class: 'atmospheric_pressure', state_class: 'measurement'},
presence_timeout: {entity_category: 'config', icon: 'mdi:timer'},
reporting_time: {entity_category: 'config', icon: 'mdi:clock-time-one-outline'},
requested_brightness_level: {
enabled_by_default: false,
entity_category: 'diagnostic',
icon: 'mdi:brightness-5',
},
requested_brightness_percent: {
enabled_by_default: false,
entity_category: 'diagnostic',
icon: 'mdi:brightness-5',
},
smoke_density: {icon: 'mdi:google-circles-communities', state_class: 'measurement'},
soil_moisture: {device_class: 'moisture', state_class: 'measurement'},
temperature: {device_class: 'temperature', state_class: 'measurement'},
temperature_calibration: {entity_category: 'config', icon: 'mdi:wrench-clock'},
temperature_max: {entity_category: 'config', icon: 'mdi:thermometer-plus'},
temperature_min: {entity_category: 'config', icon: 'mdi:thermometer-minus'},
temperature_offset: {icon: 'mdi:thermometer-lines'},
transition: {entity_category: 'config', icon: 'mdi:transition'},
trigger_count: {icon: 'mdi:counter', enabled_by_default: false},
voc: {device_class: 'volatile_organic_compounds', state_class: 'measurement'},
voc_index: {state_class: 'measurement', icon: 'mdi:molecule'},
voc_parts: {device_class: 'volatile_organic_compounds_parts', state_class: 'measurement'},
vibration_timeout: {entity_category: 'config', icon: 'mdi:timer'},
voltage: {
device_class: 'voltage',
enabled_by_default: false,
entity_category: 'diagnostic',
state_class: 'measurement',
},
voltage_phase_b: {
device_class: 'voltage',
enabled_by_default: false,
entity_category: 'diagnostic',
state_class: 'measurement',
},
voltage_phase_c: {
device_class: 'voltage',
enabled_by_default: false,
entity_category: 'diagnostic',
state_class: 'measurement',
},
water_consumed: {
device_class: 'water',
state_class: 'total_increasing',
},
x_axis: {icon: 'mdi:axis-x-arrow'},
y_axis: {icon: 'mdi:axis-y-arrow'},
z_axis: {icon: 'mdi:axis-z-arrow'},
} as const;
const ENUM_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
action: {icon: 'mdi:gesture-double-tap'},
alarm_humidity: {entity_category: 'config', icon: 'mdi:water-percent-alert'},
alarm_temperature: {entity_category: 'config', icon: 'mdi:thermometer-alert'},
backlight_auto_dim: {entity_category: 'config', icon: 'mdi:brightness-auto'},
backlight_mode: {entity_category: 'config', icon: 'mdi:lightbulb'},
calibrate: {icon: 'mdi:tune'},
color_power_on_behavior: {entity_category: 'config', icon: 'mdi:palette'},
control_mode: {entity_category: 'config', icon: 'mdi:tune'},
device_mode: {entity_category: 'config', icon: 'mdi:tune'},
effect: {enabled_by_default: false, icon: 'mdi:palette'},
force: {entity_category: 'config', icon: 'mdi:valve'},
keep_time: {entity_category: 'config', icon: 'mdi:av-timer'},
identify: {device_class: 'identify'},
keypad_lockout: {entity_category: 'config', icon: 'mdi:lock'},
load_detection_mode: {entity_category: 'config', icon: 'mdi:tune'},
load_dimmable: {entity_category: 'config', icon: 'mdi:chart-bell-curve'},
load_type: {entity_category: 'config', icon: 'mdi:led-on'},
melody: {entity_category: 'config', icon: 'mdi:music-note'},
mode_phase_control: {entity_category: 'config', icon: 'mdi:tune'},
mode: {entity_category: 'config', icon: 'mdi:tune'},
mode_switch: {icon: 'mdi:tune'},
motion_sensitivity: {entity_category: 'config', icon: 'mdi:tune'},
operation_mode: {entity_category: 'config', icon: 'mdi:tune'},
power_on_behavior: {entity_category: 'config', icon: 'mdi:power-settings'},
power_outage_memory: {entity_category: 'config', icon: 'mdi:power-settings'},
power_supply_mode: {entity_category: 'config', icon: 'mdi:power-settings'},
power_type: {entity_category: 'config', icon: 'mdi:lightning-bolt-circle'},
restart: {device_class: 'restart'},
sensitivity: {entity_category: 'config', icon: 'mdi:tune'},
sensor: {icon: 'mdi:tune'},
sensors_type: {entity_category: 'config', icon: 'mdi:tune'},
sound_volume: {entity_category: 'config', icon: 'mdi:volume-high'},
status: {icon: 'mdi:state-machine'},
switch_type: {entity_category: 'config', icon: 'mdi:tune'},
temperature_display_mode: {entity_category: 'config', icon: 'mdi:thermometer'},
temperature_sensor_select: {entity_category: 'config', icon: 'mdi:home-thermometer'},
thermostat_unit: {entity_category: 'config', icon: 'mdi:thermometer'},
update: {device_class: 'update'},
volume: {entity_category: 'config', icon: 'mdi: volume-high'},
week: {entity_category: 'config', icon: 'mdi:calendar-clock'},
} as const;
const LIST_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
action: {icon: 'mdi:gesture-double-tap'},
color_options: {icon: 'mdi:palette'},
level_config: {entity_category: 'diagnostic'},
programming_mode: {icon: 'mdi:calendar-clock'},
schedule_settings: {icon: 'mdi:calendar-clock'},
} as const;
const featurePropertyWithoutEndpoint = (feature: zhc.Feature): string => {
if (feature.endpoint) {
return feature.property.slice(0, -1 + -1 * feature.endpoint.length);
} else {
return feature.property;
}
};
/**
* This class handles the bridge entity configuration for Home Assistant Discovery.
*/
class Bridge {
private coordinatorIeeeAddress: string;
private coordinatorType: string;
private coordinatorFirmwareVersion: string;
private discoveryEntries: DiscoveryEntry[];
readonly options: {
ID?: string;
homeassistant?: KeyValue;
};
get ID(): string {
return this.coordinatorIeeeAddress;
}
get name(): string {
return 'bridge';
}
get hardwareVersion(): string {
return this.coordinatorType;
}
get firmwareVersion(): string {
return this.coordinatorFirmwareVersion;
}
get configs(): DiscoveryEntry[] {
return this.discoveryEntries;
}
constructor(ieeeAdress: string, version: zh.CoordinatorVersion, discovery: DiscoveryEntry[]) {
this.coordinatorIeeeAddress = ieeeAdress;
this.coordinatorType = version.type;
/* istanbul ignore next */
this.coordinatorFirmwareVersion = version.meta.revision ? `${version.meta.revision}` : '';
this.discoveryEntries = discovery;
this.options = {
ID: `bridge_${ieeeAdress}`,
homeassistant: {
name: `Zigbee2MQTT Bridge`,
},
};
}
isDevice(): this is Device {
return false;
}
isGroup(): this is Group {
return false;
}
}
/**
* This extensions handles integration with HomeAssistant
*/
export default class HomeAssistant extends Extension {
private discovered: {[s: string]: Discovered} = {};
private discoveryTopic: string;
private discoveryRegex: RegExp;
private discoveryRegexWoTopic = new RegExp(`(.*)/(.*)/(.*)/config`);
private statusTopic: string;
private entityAttributes: boolean;
private legacyTrigger: boolean;
private experimentalEventEntities: boolean;
// @ts-expect-error initialized in `start`
private zigbee2MQTTVersion: string;
// @ts-expect-error initialized in `start`
private discoveryOrigin: {name: string; sw: string; url: string};
// @ts-expect-error initialized in `start`
private bridge: Bridge;
// @ts-expect-error initialized in `start`
private bridgeIdentifier: string;
private actionValueTemplate: string;
constructor(
zigbee: Zigbee,
mqtt: MQTT,
state: State,
publishEntityState: PublishEntityState,
eventBus: EventBus,
enableDisableExtension: (enable: boolean, name: string) => Promise<void>,
restartCallback: () => Promise<void>,
addExtension: (extension: Extension) => Promise<void>,
) {
super(zigbee, mqtt, state, publishEntityState, eventBus, enableDisableExtension, restartCallback, addExtension);
if (settings.get().advanced.output === 'attribute') {
throw new Error('Home Assistant integration is not possible with attribute output!');
}
const haSettings = settings.get().homeassistant;
assert(haSettings, 'Home Assistant extension used without settings');
this.discoveryTopic = haSettings.discovery_topic;
this.discoveryRegex = new RegExp(`${haSettings.discovery_topic}/(.*)/(.*)/(.*)/config`);
this.statusTopic = haSettings.status_topic;
this.entityAttributes = haSettings.legacy_entity_attributes;
this.legacyTrigger = haSettings.legacy_triggers;
this.experimentalEventEntities = haSettings.experimental_event_entities;
if (haSettings.discovery_topic === settings.get().mqtt.base_topic) {
throw new Error(`'homeassistant.discovery_topic' cannot not be equal to the 'mqtt.base_topic' (got '${settings.get().mqtt.base_topic}')`);
}
this.actionValueTemplate = this.getActionValueTemplate();
}
override async start(): Promise<void> {
if (!settings.get().advanced.cache_state) {
logger.warning('In order for Home Assistant integration to work properly set `cache_state: true');
}
this.zigbee2MQTTVersion = (await utils.getZigbee2MQTTVersion(false)).version;
this.discoveryOrigin = {name: 'Zigbee2MQTT', sw: this.zigbee2MQTTVersion, url: 'https://www.zigbee2mqtt.io'};
this.bridge = this.getBridgeEntity(await this.zigbee.getCoordinatorVersion());
this.bridgeIdentifier = this.getDevicePayload(this.bridge).identifiers[0];
this.eventBus.onEntityRemoved(this, this.onEntityRemoved);
this.eventBus.onMQTTMessage(this, this.onMQTTMessage);
this.eventBus.onEntityRenamed(this, this.onEntityRenamed);
this.eventBus.onPublishEntityState(this, this.onPublishEntityState);
this.eventBus.onGroupMembersChanged(this, this.onGroupMembersChanged);
this.eventBus.onDeviceAnnounce(this, this.onZigbeeEvent);
this.eventBus.onDeviceJoined(this, this.onZigbeeEvent);
this.eventBus.onDeviceInterview(this, this.onZigbeeEvent);
this.eventBus.onDeviceMessage(this, this.onZigbeeEvent);
this.eventBus.onScenesChanged(this, this.onScenesChanged);
this.eventBus.onEntityOptionsChanged(this, async (data) => await this.discover(data.entity));
this.eventBus.onExposesChanged(this, async (data) => await this.discover(data.device));
this.mqtt.subscribe(this.statusTopic);
this.mqtt.subscribe(DEFAULT_STATUS_TOPIC);
/**
* Prevent unnecessary re-discovery of entities by waiting 5 seconds for retained discovery messages to come in.
* Any received discovery messages will not be published again.
* Unsubscribe from the discoveryTopic to prevent receiving our own messages.
*/
const discoverWait = 5;
// Discover with `published = false`, this will populate `this.discovered` without publishing the discoveries.
// This is needed for clearing outdated entries in `this.onMQTTMessage()`
await this.discover(this.bridge, false);
for (const e of this.zigbee.devicesAndGroupsIterator(utils.deviceNotCoordinator)) {
await this.discover(e, false);
}
logger.debug(`Discovering entities to Home Assistant in ${discoverWait}s`);
this.mqtt.subscribe(`${this.discoveryTopic}/#`);
setTimeout(async () => {
this.mqtt.unsubscribe(`${this.discoveryTopic}/#`);
logger.debug(`Discovering entities to Home Assistant`);
await this.discover(this.bridge);
for (const e of this.zigbee.devicesAndGroupsIterator(utils.deviceNotCoordinator)) {
await this.discover(e);
}
}, utils.seconds(discoverWait));
// Send availability messages, this is required if the legacy_availability_payload option has been changed.
this.eventBus.emitPublishAvailability();
}
private getDiscovered(entity: Device | Group | Bridge | string | number): Discovered {
const ID = typeof entity === 'string' || typeof entity === 'number' ? entity : entity.ID;
if (!(ID in this.discovered)) {
this.discovered[ID] = {messages: {}, triggers: new Set(), mockProperties: new Set(), discovered: false};
}
return this.discovered[ID];
}
private exposeToConfig(
exposes: zhc.Expose[],
entityType: 'device' | 'group',
allExposes: zhc.Expose[],
definition?: zhc.Definition,
): DiscoveryEntry[] {
// For groups an array of exposes (of the same type) is passed, this is to determine e.g. what features
// to use for a bulb (e.g. color_xy/color_temp)
assert(entityType === 'group' || exposes.length === 1, 'Multiple exposes for device not allowed');
const firstExpose = exposes[0];
assert(entityType === 'device' || GROUP_SUPPORTED_TYPES.includes(firstExpose.type), `Unsupported expose type ${firstExpose.type} for group`);
const discoveryEntries: DiscoveryEntry[] = [];
const endpoint = entityType === 'device' ? exposes[0].endpoint : undefined;
const getProperty = (feature: zhc.Feature): string => (entityType === 'group' ? featurePropertyWithoutEndpoint(feature) : feature.property);
switch (firstExpose.type) {
case 'light': {
const hasColorXY = (exposes as zhc.Light[]).find((expose) => expose.features.find((e) => e.name === 'color_xy'));
const hasColorHS = (exposes as zhc.Light[]).find((expose) => expose.features.find((e) => e.name === 'color_hs'));
const hasBrightness = (exposes as zhc.Light[]).find((expose) => expose.features.find((e) => e.name === 'brightness'));
const hasColorTemp = (exposes as zhc.Light[]).find((expose) => expose.features.find((e) => e.name === 'color_temp'));
const state = (firstExpose as zhc.Light).features.find((f) => f.name === 'state');
assert(state, `Light expose must have a 'state'`);
// Prefer HS over XY when at least one of the lights in the group prefers HS over XY.
// A light prefers HS over XY when HS is earlier in the feature array than HS.
const preferHS =
(exposes as zhc.Light[])
.map((e) => [e.features.findIndex((ee) => ee.name === 'color_xy'), e.features.findIndex((ee) => ee.name === 'color_hs')])
.filter((d) => d[0] !== -1 && d[1] !== -1 && d[1] < d[0]).length !== 0;
const discoveryEntry: DiscoveryEntry = {
type: 'light',
object_id: endpoint ? `light_${endpoint}` : 'light',
mockProperties: [{property: state.property, value: null}],
discovery_payload: {
name: endpoint ? utils.capitalize(endpoint) : null,
brightness: !!hasBrightness,
schema: 'json',
command_topic: true,
brightness_scale: 254,
command_topic_prefix: endpoint,
state_topic_postfix: endpoint,
},
};
const colorModes = [
hasColorXY && !preferHS ? 'xy' : null,
(!hasColorXY || preferHS) && hasColorHS ? 'hs' : null,
hasColorTemp ? 'color_temp' : null,
].filter((c) => c);
if (colorModes.length) {
discoveryEntry.discovery_payload.supported_color_modes = colorModes;
}
if (hasColorTemp) {
const colorTemps = (exposes as zhc.Light[])
.map((expose) => expose.features.find((e) => e.name === 'color_temp'))
.filter((e) => e !== undefined && isNumericExpose(e));
const max = Math.min(...colorTemps.map((e) => e.value_max).filter((e) => e !== undefined));
const min = Math.max(...colorTemps.map((e) => e.value_min).filter((e) => e !== undefined));
discoveryEntry.discovery_payload.max_mireds = max;
discoveryEntry.discovery_payload.min_mireds = min;
}
const effects = utils.arrayUnique(
utils.flatten(
allExposes
.filter(isEnumExpose)
.filter((e) => e.name === 'effect')
.map((e) => e.values),
),
);
if (effects.length) {
discoveryEntry.discovery_payload.effect = true;
discoveryEntry.discovery_payload.effect_list = effects;
}
discoveryEntries.push(discoveryEntry);
break;
}
case 'switch': {
const state = (firstExpose as zhc.Switch).features.filter(isBinaryExpose).find((f) => f.name === 'state');
assert(state, `Switch expose must have a 'state'`);
const property = getProperty(state);
const discoveryEntry: DiscoveryEntry = {
type: 'switch',
object_id: endpoint ? `switch_${endpoint}` : 'switch',
mockProperties: [{property: property, value: null}],
discovery_payload: {
name: endpoint ? utils.capitalize(endpoint) : null,
payload_off: state.value_off,
payload_on: state.value_on,
value_template: `{{ value_json.${property} }}`,
command_topic: true,
command_topic_prefix: endpoint,
},
};
if (SWITCH_DIFFERENT.includes(property)) {
discoveryEntry.discovery_payload.name = firstExpose.label;
discoveryEntry.discovery_payload.command_topic_postfix = property;
discoveryEntry.discovery_payload.state_off = state.value_off;
discoveryEntry.discovery_payload.state_on = state.value_on;
discoveryEntry.object_id = property;
if (property === 'window_detection') {
discoveryEntry.discovery_payload.icon = 'mdi:window-open-variant';
}
}
discoveryEntries.push(discoveryEntry);
break;
}
case 'climate': {
const setpointProperties = ['occupied_heating_setpoint', 'current_heating_setpoint'];
const setpoint = (firstExpose as zhc.Climate).features.filter(isNumericExpose).find((f) => setpointProperties.includes(f.name));
assert(
setpoint && setpoint.value_min !== undefined && setpoint.value_max !== undefined,
'No setpoint found or it is missing value_min/max',
);
const temperature = (firstExpose as zhc.Climate).features.find((f) => f.name === 'local_temperature');
assert(temperature, 'No temperature found');
const discoveryEntry: DiscoveryEntry = {
type: 'climate',
object_id: endpoint ? `climate_${endpoint}` : 'climate',
mockProperties: [],
discovery_payload: {
name: endpoint ? utils.capitalize(endpoint) : null,
// Static
state_topic: false,
temperature_unit: 'C',
// Setpoint
temp_step: setpoint.value_step,
min_temp: setpoint.value_min.toString(),
max_temp: setpoint.value_max.toString(),
// Temperature
current_temperature_topic: true,
current_temperature_template: `{{ value_json.${temperature.property} }}`,
command_topic_prefix: endpoint,
},
};
const mode = (firstExpose as zhc.Climate).features.filter(isEnumExpose).find((f) => f.name === 'system_mode');
if (mode) {
if (mode.values.includes('sleep')) {
// 'sleep' is not supported by Home Assistant, but is valid according to ZCL
// TRV that support sleep (e.g. Viessmann) will have it removed from here,
// this allows other expose consumers to still use it, e.g. the frontend.
mode.values.splice(mode.values.indexOf('sleep'), 1);
}
discoveryEntry.discovery_payload.mode_state_topic = true;
discoveryEntry.discovery_payload.mode_state_template = `{{ value_json.${mode.property} }}`;
discoveryEntry.discovery_payload.modes = mode.values;
discoveryEntry.discovery_payload.mode_command_topic = true;
}
const state = (firstExpose as zhc.Climate).features.find((f) => f.name === 'running_state');
if (state) {
discoveryEntry.mockProperties.push({property: state.property, value: null});
discoveryEntry.discovery_payload.action_topic = true;
discoveryEntry.discovery_payload.action_template =
`{% set values = ` +
`{None:None,'idle':'idle','heat':'heating','cool':'cooling','fan_only':'fan'}` +
` %}{{ values[value_json.${state.property}] }}`;
}
const coolingSetpoint = (firstExpose as zhc.Climate).features.find((f) => f.name === 'occupied_cooling_setpoint');
if (coolingSetpoint) {
discoveryEntry.discovery_payload.temperature_low_command_topic = setpoint.name;
discoveryEntry.discovery_payload.temperature_low_state_template = `{{ value_json.${setpoint.property} }}`;
discoveryEntry.discovery_payload.temperature_low_state_topic = true;
discoveryEntry.discovery_payload.temperature_high_command_topic = coolingSetpoint.name;
discoveryEntry.discovery_payload.temperature_high_state_template = `{{ value_json.${coolingSetpoint.property} }}`;
discoveryEntry.discovery_payload.temperature_high_state_topic = true;
} else {
discoveryEntry.discovery_payload.temperature_command_topic = setpoint.name;
discoveryEntry.discovery_payload.temperature_state_template = `{{ value_json.${setpoint.property} }}`;
discoveryEntry.discovery_payload.temperature_state_topic = true;
}
const fanMode = (firstExpose as zhc.Climate).features.filter(isEnumExpose).find((f) => f.name === 'fan_mode');
if (fanMode) {
discoveryEntry.discovery_payload.fan_modes = fanMode.values;
discoveryEntry.discovery_payload.fan_mode_command_topic = true;
discoveryEntry.discovery_payload.fan_mode_state_template = `{{ value_json.${fanMode.property} }}`;
discoveryEntry.discovery_payload.fan_mode_state_topic = true;
}
const swingMode = (firstExpose as zhc.Climate).features.filter(isEnumExpose).find((f) => f.name === 'swing_mode');
if (swingMode) {
discoveryEntry.discovery_payload.swing_modes = swingMode.values;
discoveryEntry.discovery_payload.swing_mode_command_topic = true;
discoveryEntry.discovery_payload.swing_mode_state_template = `{{ value_json.${swingMode.property} }}`;
discoveryEntry.discovery_payload.swing_mode_state_topic = true;
}
const preset = (firstExpose as zhc.Climate).features.filter(isEnumExpose).find((f) => f.name === 'preset');
if (preset) {
discoveryEntry.discovery_payload.preset_modes = preset.values;
discoveryEntry.discovery_payload.preset_mode_command_topic = 'preset';
discoveryEntry.discovery_payload.preset_mode_value_template = `{{ value_json.${preset.property} }}`;
discoveryEntry.discovery_payload.preset_mode_state_topic = true;
}
const tempCalibration = (firstExpose as zhc.Climate).features
.filter(isNumericExpose)
.find((f) => f.name === 'local_temperature_calibration');
if (tempCalibration) {
const discoveryEntry: DiscoveryEntry = {
type: 'number',
object_id: endpoint ? `${tempCalibration.name}_${endpoint}` : `${tempCalibration.name}`,
mockProperties: [{property: tempCalibration.property, value: null}],
discovery_payload: {
name: endpoint ? `${tempCalibration.label} ${endpoint}` : tempCalibration.label,
value_template: `{{ value_json.${tempCalibration.property} }}`,
command_topic: true,
command_topic_prefix: endpoint,
command_topic_postfix: tempCalibration.property,
device_class: 'temperature',
entity_category: 'config',
icon: 'mdi:math-compass',
...(tempCalibration.unit && {unit_of_measurement: tempCalibration.unit}),
},
};
// istanbul ignore else
if (tempCalibration.value_min != null) discoveryEntry.discovery_payload.min = tempCalibration.value_min;
// istanbul ignore else
if (tempCalibration.value_max != null) discoveryEntry.discovery_payload.max = tempCalibration.value_max;
// istanbul ignore else
if (tempCalibration.value_step != null) {
discoveryEntry.discovery_payload.step = tempCalibration.value_step;
}
discoveryEntries.push(discoveryEntry);
}
const piHeatingDemand = (firstExpose as zhc.Climate).features.filter(isNumericExpose).find((f) => f.name === 'pi_heating_demand');
if (piHeatingDemand) {
const discoveryEntry: DiscoveryEntry = {
type: 'sensor',
object_id: endpoint ? /* istanbul ignore next */ `${piHeatingDemand.name}_${endpoint}` : `${piHeatingDemand.name}`,
mockProperties: [{property: piHeatingDemand.property, value: null}],
discovery_payload: {
name: endpoint ? /* istanbul ignore next */ `${piHeatingDemand.label} ${endpoint}` : piHeatingDemand.label,
value_template: `{{ value_json.${piHeatingDemand.property} }}`,
...(piHeatingDemand.unit && {unit_of_measurement: piHeatingDemand.unit}),
entity_category: 'diagnostic',
icon: 'mdi:radiator',
},
};
discoveryEntries.push(discoveryEntry);
}
discoveryEntries.push(discoveryEntry);
break;
}
case 'lock': {
assert(!endpoint, `Endpoint not supported for lock type`);
const state = (firstExpose as zhc.Lock).features.filter(isBinaryExpose).find((f) => f.name === 'state');
assert(state, `Lock expose must have a 'state'`);
const discoveryEntry: DiscoveryEntry = {
type: 'lock',
object_id: 'lock',
mockProperties: [{property: state.property, value: null}],
discovery_payload: {
name: null,
command_topic: true,
value_template: `{{ value_json.${state.property} }}`,
},
};
// istanbul ignore if
if (state.property === 'keypad_lockout') {
// deprecated: keypad_lockout is messy, but changing is breaking
discoveryEntry.discovery_payload.name = firstExpose.label;
discoveryEntry.discovery_payload.payload_lock = state.value_on;
discoveryEntry.discovery_payload.payload_unlock = state.value_off;
discoveryEntry.discovery_payload.state_topic = true;
discoveryEntry.object_id = 'keypad_lock';
} else if (state.property === 'child_lock') {
// deprecated: child_lock is messy, but changing is breaking
discoveryEntry.discovery_payload.name = firstExpose.label;
discoveryEntry.discovery_payload.payload_lock = state.value_on;
discoveryEntry.discovery_payload.payload_unlock = state.value_off;
discoveryEntry.discovery_payload.state_locked = 'LOCK';
discoveryEntry.discovery_payload.state_unlocked = 'UNLOCK';
discoveryEntry.discovery_payload.state_topic = true;
discoveryEntry.object_id = 'child_lock';
} else {
discoveryEntry.discovery_payload.state_locked = state.value_on;
discoveryEntry.discovery_payload.state_unlocked = state.value_off;
}
if (state.property !== 'state') {
discoveryEntry.discovery_payload.command_topic_postfix = state.property;
}
discoveryEntries.push(discoveryEntry);
break;
}
case 'cover': {
const state = (exposes as zhc.Cover[])
.find((expose) => expose.features.find((e) => e.name === 'state'))
?.features.find((f) => f.name === 'state');
assert(state, `Cover expose must have a 'state'`);
const position = (exposes as zhc.Cover[])
.find((expose) => expose.features.find((e) => e.name === 'position'))
?.features.find((f) => f.name === 'position');
const tilt = (exposes as zhc.Cover[])
.find((expose) => expose.features.find((e) => e.name === 'tilt'))
?.features.find((f) => f.name === 'tilt');
const motorState = allExposes
?.filter(isEnumExpose)
.find((e) => ['motor_state', 'moving'].includes(e.name) && e.access === ACCESS_STATE);
const running = allExposes?.find((e) => e.type === 'binary' && e.name === 'running');
const discoveryEntry: DiscoveryEntry = {
type: 'cover',
mockProperties: [{property: state.property, value: null}],
object_id: endpoint ? `cover_${endpoint}` : 'cover',
discovery_payload: {
name: endpoint ? utils.capitalize(endpoint) : null,
command_topic_prefix: endpoint,
command_topic: true,
state_topic: true,
state_topic_postfix: endpoint,
},
};
// If curtains have `running` property, use this in discovery.
// The movement direction is calculated (assumed) in this case.
if (running) {
assert(position, `Cover must have 'position' when it has 'running'`);
discoveryEntry.discovery_payload.value_template =
`{% if "${running.property}" in value_json ` +
`and value_json.${running.property} %} {% if value_json.${position.property} > 0 %} closing ` +
`{% else %} opening {% endif %} {% else %} stopped {% endif %}`;
}
// If curtains have `motor_state` or `moving` property, lookup for possible
// state names to detect movement direction and use this in discovery.
if (motorState) {
const openingState = motorState.values.find((s) => COVER_OPENING_LOOKUP.includes(s.toString().toLowerCase()));
const closingState = motorState.values.find((s) => COVER_CLOSING_LOOKUP.includes(s.toString().toLowerCase()));
const stoppedState = motorState.values.find((s) => COVER_STOPPED_LOOKUP.includes(s.toString().toLowerCase()));
// istanbul ignore else
if (openingState && closingState && stoppedState) {
discoveryEntry.discovery_payload.state_opening = openingState;
discoveryEntry.discovery_payload.state_closing = closingState;
discoveryEntry.discovery_payload.state_stopped = stoppedState;
discoveryEntry.discovery_payload.value_template =
`{% if "${motorState.property}" in value_json ` +
`and value_json.${motorState.property} %} {{ value_json.${motorState.property} }} {% else %} ` +
`${stoppedState} {% endif %}`;
}
}
// If curtains do not have `running`, `motor_state` or `moving` properties.
if (!discoveryEntry.discovery_payload.value_template) {
discoveryEntry.discovery_payload.value_template = `{{ value_json.${featurePropertyWithoutEndpoint(state)} }}`;
discoveryEntry.discovery_payload.state_open = 'OPEN';
discoveryEntry.discovery_payload.state_closed = 'CLOSE';
discoveryEntry.discovery_payload.state_stopped = 'STOP';
}
// istanbul ignore if
if (!position && !tilt) {
discoveryEntry.discovery_payload.optimistic = true;
}
if (position) {
discoveryEntry.discovery_payload = {
...discoveryEntry.discovery_payload,
position_template: `{{ value_json.${featurePropertyWithoutEndpoint(position)} }}`,
set_position_template: `{ "${getProperty(position)}": {{ position }} }`,
set_position_topic: true,
position_topic: true,
};
}
if (tilt) {
discoveryEntry.discovery_payload = {
...discoveryEntry.discovery_payload,
tilt_command_topic: true,
tilt_status_topic: true,
tilt_status_template: `{{ value_json.${featurePropertyWithoutEndpoint(tilt)} }}`,
};
}
discoveryEntries.push(discoveryEntry);
break;
}
case 'fan': {
assert(!endpoint, `Endpoint not supported for fan type`);
const discoveryEntry: DiscoveryEntry = {
type: 'fan',
object_id: 'fan',
mockProperties: [{property: 'fan_state', value: null}],
discovery_payload: {
name: null,
state_topic: true,
state_value_template: '{{ value_json.fan_state }}',
command_topic: true,
command_topic_postfix: 'fan_state',
},
};
const speed = (firstExpose as zhc.Fan).features.filter(isEnumExpose).find((e) => e.name === 'mode');
// istanbul ignore else
if (speed) {
// A fan entity in Home Assistant 2021.3 and above may have a speed,
// controlled by a percentage from 1 to 100, and/or non-speed presets.
// The MQTT Fan integration allows the speed percentage to be mapped
// to a narrower range of speeds (e.g. 1-3), and for these speeds to be
// translated to and from MQTT messages via templates.
//
// For the fixed fan modes in ZCL hvacFanCtrl, we model speeds "low",
// "medium", and "high" as three speeds covering the full percentage
// range as done in Home Assistant's zigpy fan integration, plus
// presets "on", "auto" and "smart" to cover the remaining modes in
// ZCL. This supports a generic ZCL HVAC Fan Control fan. "Off" is
// always a valid speed.
let speeds = ['off'].concat(
['low', 'medium', 'high', '1', '2', '3', '4', '5', '6', '7', '8', '9'].filter((s) => speed.values.includes(s)),
);
let presets = ['on', 'auto', 'smart'].filter((s) => speed.values.includes(s));
if (['99432'].includes(definition!.model)) {
// The Hampton Bay 99432 fan implements 4 speeds using the ZCL
// hvacFanCtrl values `low`, `medium`, `high`, and `on`, and
// 1 preset called "Comfort Breeze" using the ZCL value `smart`.
// ZCL value `auto` is unused.
speeds = ['off', 'low', 'medium', 'high', 'on'];
presets = ['smart'];
}
const allowed = [...speeds, ...presets];
speed.values.forEach((s) => assert(allowed.includes(s.toString())));