-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathmodernExtend.ts
2514 lines (2274 loc) · 101 KB
/
modernExtend.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 {Zcl} from 'zigbee-herdsman';
import {ClusterDefinition} from 'zigbee-herdsman/dist/zspec/zcl/definition/tstype';
import fz from '../converters/fromZigbee';
import tz from '../converters/toZigbee';
import {logger} from '../lib/logger';
import * as globalStore from '../lib/store';
import {Cover, presets as e, access as ea, Numeric, options as opt} from './exposes';
import {configure as lightConfigure} from './light';
import {
Access,
BatteryLinearVoltage,
BatteryNonLinearVoltage,
Configure,
DefinitionExposes,
DefinitionExposesFunction,
DefinitionMeta,
Expose,
Fz,
KeyValue,
KeyValueAny,
KeyValueString,
ModernExtend,
OnEvent,
Range,
Tz,
Zh,
} from './types';
import {
addActionGroup,
assertNumber,
batteryVoltageToPercentage,
configureSetPowerSourceWhenUnknown,
exposeEndpoints,
flatten,
getEndpointName,
getFromLookup,
getFromLookupByValue,
getOptions,
hasAlreadyProcessedMessage,
isEndpoint,
isNumber,
isObject,
isString,
noOccupancySince,
postfixWithEndpointName,
precisionRound,
splitArrayIntoChunks,
} from './utils';
function getEndpointsWithCluster(device: Zh.Device, cluster: string | number, type: 'input' | 'output') {
if (!device.endpoints) {
throw new Error(device.ieeeAddr + ' ' + device.endpoints);
}
const endpoints =
type === 'input'
? device.endpoints.filter((ep) => ep.getInputClusters().find((c) => (isNumber(cluster) ? c.ID === cluster : c.name === cluster)))
: device.endpoints.filter((ep) => ep.getOutputClusters().find((c) => (isNumber(cluster) ? c.ID === cluster : c.name === cluster)));
if (endpoints.length === 0) {
throw new Error(`Device ${device.ieeeAddr} has no ${type} cluster ${cluster}`);
}
return endpoints;
}
const IAS_EXPOSE_LOOKUP = {
occupancy: e.binary('occupancy', ea.STATE, true, false).withDescription('Indicates whether the device detected occupancy'),
contact: e.binary('contact', ea.STATE, false, true).withDescription('Indicates whether the device is opened or closed'),
smoke: e.binary('smoke', ea.STATE, true, false).withDescription('Indicates whether the device detected smoke'),
water_leak: e.binary('water_leak', ea.STATE, true, false).withDescription('Indicates whether the device detected a water leak'),
carbon_monoxide: e.binary('carbon_monoxide', ea.STATE, true, false).withDescription('Indicates whether the device detected carbon monoxide'),
sos: e.binary('sos', ea.STATE, true, false).withLabel('SOS').withDescription('Indicates whether the SOS alarm is triggered'),
vibration: e.binary('vibration', ea.STATE, true, false).withDescription('Indicates whether the device detected vibration'),
alarm: e.binary('alarm', ea.STATE, true, false).withDescription('Indicates whether the alarm is triggered'),
gas: e.binary('gas', ea.STATE, true, false).withDescription('Indicates whether the device detected gas'),
alarm_1: e.binary('alarm_1', ea.STATE, true, false).withDescription('Indicates whether IAS Zone alarm 1 is active'),
alarm_2: e.binary('alarm_2', ea.STATE, true, false).withDescription('Indicates whether IAS Zone alarm 2 is active'),
tamper: e.binary('tamper', ea.STATE, true, false).withDescription('Indicates whether the device is tampered').withCategory('diagnostic'),
rain: e.binary('rain', ea.STATE, true, false).withDescription('Indicates whether the device detected rainfall'),
battery_low: e
.binary('battery_low', ea.STATE, true, false)
.withDescription('Indicates whether the battery of the device is almost empty')
.withCategory('diagnostic'),
supervision_reports: e
.binary('supervision_reports', ea.STATE, true, false)
.withDescription('Indicates whether the device issues reports on zone operational status')
.withCategory('diagnostic'),
restore_reports: e
.binary('restore_reports', ea.STATE, true, false)
.withDescription('Indicates whether the device issues reports on alarm no longer being present')
.withCategory('diagnostic'),
ac_status: e
.binary('ac_status', ea.STATE, true, false)
.withDescription('Indicates whether the device mains voltage supply is at fault')
.withCategory('diagnostic'),
test: e
.binary('test', ea.STATE, true, false)
.withDescription('Indicates whether the device is currently performing a test')
.withCategory('diagnostic'),
trouble: e
.binary('trouble', ea.STATE, true, false)
.withDescription('Indicates whether the device is currently havin trouble')
.withCategory('diagnostic'),
battery_defect: e
.binary('battery_defect', ea.STATE, true, false)
.withDescription('Indicates whether the device battery is defective')
.withCategory('diagnostic'),
};
export const TIME_LOOKUP = {
MAX: 65000,
'4_HOURS': 14400,
'1_HOUR': 3600,
'30_MINUTES': 1800,
'5_MINUTES': 300,
'2_MINUTES': 120,
'1_MINUTE': 60,
'10_SECONDS': 10,
'5_SECONDS': 5,
'1_SECOND': 1,
MIN: 0,
};
type ReportingConfigTime = number | keyof typeof TIME_LOOKUP;
type ReportingConfigAttribute = string | number | {ID: number; type: number};
type ReportingConfig = {min: ReportingConfigTime; max: ReportingConfigTime; change: number; attribute: ReportingConfigAttribute};
export type ReportingConfigWithoutAttribute = Omit<ReportingConfig, 'attribute'>;
function convertReportingConfigTime(time: ReportingConfigTime): number {
if (isString(time)) {
if (!(time in TIME_LOOKUP)) throw new Error(`Reporting time '${time}' is unknown`);
return TIME_LOOKUP[time];
} else {
return time;
}
}
export async function setupAttributes(
entity: Zh.Device | Zh.Endpoint,
coordinatorEndpoint: Zh.Endpoint,
cluster: string | number,
config: ReportingConfig[],
configureReporting: boolean = true,
read: boolean = true,
) {
const endpoints = isEndpoint(entity) ? [entity] : getEndpointsWithCluster(entity, cluster, 'input');
const ieeeAddr = isEndpoint(entity) ? entity.deviceIeeeAddress : entity.ieeeAddr;
for (const endpoint of endpoints) {
logger.debug(
`Configure reporting: ${configureReporting}, read: ${read} for ${ieeeAddr}/${endpoint.ID} ${cluster} ${JSON.stringify(config)}`,
'zhc:setupattribute',
);
// Split into chunks of 4 to prevent to message becoming too big.
const chunks = splitArrayIntoChunks(config, 4);
if (configureReporting) {
await endpoint.bind(cluster, coordinatorEndpoint);
for (const chunk of chunks) {
await endpoint.configureReporting(
cluster,
chunk.map((a) => ({
minimumReportInterval: convertReportingConfigTime(a.min),
maximumReportInterval: convertReportingConfigTime(a.max),
reportableChange: a.change,
attribute: a.attribute,
})),
);
}
}
if (read) {
for (const chunk of chunks) {
try {
// Don't fail configuration if reading this attribute fails
// https://github.com/Koenkk/zigbee-herdsman-converters/pull/7074
await endpoint.read(
cluster,
chunk.map((a) => (isString(a) ? a : isObject(a.attribute) ? a.attribute.ID : a.attribute)),
);
} catch (e) {
logger.debug(`Reading attribute failed: ${e}`, 'zhc:setupattribute');
}
}
}
}
}
export function setupConfigureForReporting(
cluster: string | number,
attribute: ReportingConfigAttribute,
config: ReportingConfigWithoutAttribute,
access: Access,
endpointNames?: string[],
) {
const configureReporting = !!config;
const read = !!(access & ea.GET);
if (configureReporting || read) {
const configure: Configure = async (device, coordinatorEndpoint, definition) => {
const reportConfig = config ? {...config, attribute: attribute} : {attribute, min: -1, max: -1, change: -1};
let entities: (Zh.Device | Zh.Endpoint)[] = [device];
if (endpointNames) {
const definitionEndpoints = definition.endpoint(device);
const endpointIds = endpointNames.map((e) => definitionEndpoints[e]);
entities = device.endpoints.filter((e) => endpointIds.includes(e.ID));
}
for (const entity of entities) {
await setupAttributes(entity, coordinatorEndpoint, cluster, [reportConfig], configureReporting, read);
}
};
return configure;
} else {
return undefined;
}
}
export function setupConfigureForBinding(cluster: string | number, clusterType: 'input' | 'output', endpointNames?: string[]) {
const configure: Configure = async (device, coordinatorEndpoint, definition) => {
if (endpointNames) {
const definitionEndpoints = definition.endpoint(device);
const endpointIds = endpointNames.map((e) => definitionEndpoints[e]);
const endpoints = device.endpoints.filter((e) => endpointIds.includes(e.ID));
for (const endpoint of endpoints) {
await endpoint.bind(cluster, coordinatorEndpoint);
}
} else {
const endpoints = getEndpointsWithCluster(device, cluster, clusterType);
for (const endpoint of endpoints) {
await endpoint.bind(cluster, coordinatorEndpoint);
}
}
};
return configure;
}
export function setupConfigureForReading(cluster: string | number, attributes: (string | number)[], endpointNames?: string[]) {
const configure: Configure = async (device, coordinatorEndpoint, definition) => {
if (endpointNames) {
const definitionEndpoints = definition.endpoint(device);
const endpointIds = endpointNames.map((e) => definitionEndpoints[e]);
const endpoints = device.endpoints.filter((e) => endpointIds.includes(e.ID));
for (const endpoint of endpoints) {
await endpoint.read(cluster, attributes);
}
} else {
const endpoints = getEndpointsWithCluster(device, cluster, 'input');
for (const endpoint of endpoints) {
await endpoint.read(cluster, attributes);
}
}
};
return configure;
}
export function determineEndpoint(entity: Zh.Endpoint | Zh.Group, meta: Tz.Meta, cluster: string | number): Zh.Endpoint | Zh.Group {
const {device, endpoint_name} = meta;
if (endpoint_name !== undefined) {
// In case an explicit endpoint is given, always send it to that endpoint
return entity;
} else {
// In case no endpoint is given, match the first endpoint which support the cluster.
return device.endpoints.find((e) => e.supportsInputCluster(cluster)) ?? device.endpoints[0];
}
}
// #region General
export function forceDeviceType(args: {type: 'EndDevice' | 'Router'}): ModernExtend {
const configure: Configure[] = [
async (device, coordinatorEndpoint, definition) => {
device.type = args.type;
device.save();
},
];
return {configure, isModernExtend: true};
}
export function forcePowerSource(args: {powerSource: 'Mains (single phase)' | 'Battery'}): ModernExtend {
const configure: Configure[] = [
async (device, coordinatorEndpoint, definition) => {
device.powerSource = args.powerSource;
device.save();
},
];
return {configure, isModernExtend: true};
}
export interface LinkQualityArgs {
reporting?: boolean;
attribute?: string | {ID: number; type: number};
reportingConfig?: ReportingConfigWithoutAttribute;
}
export function linkQuality(args?: LinkQualityArgs): ModernExtend {
args = {reporting: false, attribute: 'modelId', reportingConfig: {min: '1_HOUR', max: '4_HOURS', change: 0}, ...args};
const exposes: Expose[] = [
e
.numeric('linkquality', ea.STATE)
.withUnit('lqi')
.withDescription('Link quality (signal strength)')
.withValueMin(0)
.withValueMax(255)
.withCategory('diagnostic'),
];
const fromZigbee: Fz.Converter[] = [
{
cluster: 'genBasic',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
return {linkquality: msg.linkquality};
},
},
];
const result: ModernExtend = {exposes, fromZigbee, isModernExtend: true};
if (args.reporting) {
result.configure = [setupConfigureForReporting('genBasic', args.attribute, args.reportingConfig, ea.GET)];
}
return result;
}
export interface BatteryArgs {
voltageToPercentage?: BatteryNonLinearVoltage | BatteryLinearVoltage;
dontDividePercentage?: boolean;
percentage?: boolean;
voltage?: boolean;
lowStatus?: boolean;
percentageReportingConfig?: ReportingConfigWithoutAttribute;
percentageReporting?: boolean;
voltageReportingConfig?: ReportingConfigWithoutAttribute;
voltageReporting?: boolean;
}
export function battery(args?: BatteryArgs): ModernExtend {
args = {
percentage: true,
voltage: false,
lowStatus: false,
percentageReporting: true,
voltageReporting: false,
dontDividePercentage: false,
percentageReportingConfig: {min: '1_HOUR', max: 'MAX', change: 10},
voltageReportingConfig: {min: '1_HOUR', max: 'MAX', change: 10},
...args,
};
const exposes: Expose[] = [];
if (args.percentage) {
exposes.push(
e
.numeric('battery', ea.STATE_GET)
.withUnit('%')
.withDescription('Remaining battery in %')
.withValueMin(0)
.withValueMax(100)
.withCategory('diagnostic'),
);
}
if (args.voltage) {
exposes.push(
e.numeric('voltage', ea.STATE_GET).withUnit('mV').withDescription('Reported battery voltage in millivolts').withCategory('diagnostic'),
);
}
if (args.lowStatus) {
exposes.push(e.binary('battery_low', ea.STATE, true, false).withDescription('Empty battery indicator').withCategory('diagnostic'));
}
const fromZigbee: Fz.Converter[] = [
{
cluster: 'genPowerCfg',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const payload: KeyValueAny = {};
if (msg.data.batteryPercentageRemaining !== undefined && msg.data['batteryPercentageRemaining'] < 255) {
// Some devices do not comply to the ZCL and report a
// batteryPercentageRemaining of 100 when the battery is full (should be 200).
const dontDividePercentage = args.dontDividePercentage;
let percentage = msg.data['batteryPercentageRemaining'];
percentage = dontDividePercentage ? percentage : percentage / 2;
if (args.percentage) payload.battery = precisionRound(percentage, 2);
}
if (msg.data.batteryVoltage !== undefined && msg.data['batteryVoltage'] < 255) {
// Deprecated: voltage is = mV now but should be V
if (args.voltage) payload.voltage = msg.data['batteryVoltage'] * 100;
if (args.voltageToPercentage) {
payload.battery = batteryVoltageToPercentage(payload.voltage, args.voltageToPercentage);
}
}
if (msg.data.batteryAlarmState !== undefined) {
const battery1Low =
(msg.data.batteryAlarmState & (1 << 0) ||
msg.data.batteryAlarmState & (1 << 1) ||
msg.data.batteryAlarmState & (1 << 2) ||
msg.data.batteryAlarmState & (1 << 3)) > 0;
const battery2Low =
(msg.data.batteryAlarmState & (1 << 10) ||
msg.data.batteryAlarmState & (1 << 11) ||
msg.data.batteryAlarmState & (1 << 12) ||
msg.data.batteryAlarmState & (1 << 13)) > 0;
const battery3Low =
(msg.data.batteryAlarmState & (1 << 20) ||
msg.data.batteryAlarmState & (1 << 21) ||
msg.data.batteryAlarmState & (1 << 22) ||
msg.data.batteryAlarmState & (1 << 23)) > 0;
if (args.lowStatus) payload.battery_low = battery1Low || battery2Low || battery3Low;
}
return payload;
},
},
];
const toZigbee: Tz.Converter[] = [
{
key: ['battery', 'voltage'],
convertGet: async (entity, key, meta) => {
// Don't fail GET reqest if reading fails
// Split reading is needed for more clear debug logs
const ep = determineEndpoint(entity, meta, 'genPowerCfg');
try {
await ep.read('genPowerCfg', ['batteryPercentageRemaining']);
} catch (e) {
logger.debug(`Reading batteryPercentageRemaining failed: ${e}, device probably doesn't support it`, 'zhc:setupattribute');
}
try {
await ep.read('genPowerCfg', ['batteryVoltage']);
} catch (e) {
logger.debug(`Reading batteryVoltage failed: ${e}, device probably doesn't support it`, 'zhc:setupattribute');
}
},
},
];
const result: ModernExtend = {exposes, fromZigbee, toZigbee, isModernExtend: true};
if (args.percentageReporting || args.voltageReporting) {
const configure: Configure[] = [];
if (args.percentageReporting) {
configure.push(setupConfigureForReporting('genPowerCfg', 'batteryPercentageRemaining', args.percentageReportingConfig, ea.STATE_GET));
}
if (args.voltageReporting) {
configure.push(setupConfigureForReporting('genPowerCfg', 'batteryVoltage', args.voltageReportingConfig, ea.STATE_GET));
}
configure.push(configureSetPowerSourceWhenUnknown('Battery'));
result.configure = configure;
}
if (args.voltageToPercentage || args.dontDividePercentage) {
const meta: DefinitionMeta = {battery: {}};
if (args.voltageToPercentage) meta.battery.voltageToPercentage = args.voltageToPercentage;
if (args.dontDividePercentage) meta.battery.dontDividePercentage = args.dontDividePercentage;
result.meta = meta;
}
return result;
}
export function deviceTemperature(args?: Partial<NumericArgs>) {
return numeric({
name: 'device_temperature',
cluster: 'genDeviceTempCfg',
attribute: 'currentTemperature',
reporting: {min: '5_MINUTES', max: '1_HOUR', change: 1},
description: 'Temperature of the device',
unit: '°C',
access: 'STATE_GET',
entityCategory: 'diagnostic',
...args,
});
}
export function identify(args?: {isSleepy: boolean}): ModernExtend {
args = {isSleepy: false, ...args};
const normal: Expose = e.enum('identify', ea.SET, ['identify']).withDescription('Initiate device identification').withCategory('config');
const sleepy: Expose = e
.enum('identify', ea.SET, ['identify'])
.withDescription(
'Initiate device identification. This device is asleep by default.' +
'You may need to wake it up first before sending the identify command.',
)
.withCategory('config');
const exposes: Expose[] = args.isSleepy ? [sleepy] : [normal];
const identifyTimeout = e
.numeric('identify_timeout', ea.SET)
.withDescription(
'Sets the duration of the identification procedure in seconds (i.e., how long the device would flash).' +
'The value ranges from 1 to 30 seconds (default: 3).',
)
.withValueMin(1)
.withValueMax(30);
const toZigbee: Tz.Converter[] = [
{
key: ['identify'],
options: [identifyTimeout],
convertSet: async (entity, key, value, meta) => {
const identifyTimeout = meta.options.identify_timeout ?? 3;
await entity.command('genIdentify', 'identify', {identifytime: identifyTimeout}, getOptions(meta.mapped, entity));
},
},
];
return {exposes, toZigbee, isModernExtend: true};
}
export interface OnOffArgs {
powerOnBehavior?: boolean;
ota?: ModernExtend['ota'];
skipDuplicateTransaction?: boolean;
endpointNames?: string[];
configureReporting?: boolean;
description?: string;
}
export function onOff(args?: OnOffArgs): ModernExtend {
args = {powerOnBehavior: true, skipDuplicateTransaction: false, configureReporting: true, ...args};
const exposes: Expose[] = args.description
? exposeEndpoints(e.switch(args.description), args.endpointNames)
: exposeEndpoints(e.switch(), args.endpointNames);
const fromZigbee: Fz.Converter[] = [args.skipDuplicateTransaction ? fz.on_off_skip_duplicate_transaction : fz.on_off];
const toZigbee: Tz.Converter[] = [args?.endpointNames ? {...tz.on_off, endpoints: args?.endpointNames} : tz.on_off];
if (args.powerOnBehavior) {
exposes.push(...exposeEndpoints(e.power_on_behavior(['off', 'on', 'toggle', 'previous']), args.endpointNames));
fromZigbee.push(fz.power_on_behavior);
toZigbee.push(tz.power_on_behavior);
}
const result: ModernExtend = {exposes, fromZigbee, toZigbee, isModernExtend: true};
if (args.ota) result.ota = args.ota;
if (args.configureReporting) {
result.configure = [
async (device, coordinatorEndpoint) => {
await setupAttributes(device, coordinatorEndpoint, 'genOnOff', [{attribute: 'onOff', min: 'MIN', max: 'MAX', change: 1}]);
if (args.powerOnBehavior) {
try {
// Don't fail configure if reading this attribute fails, some devices don't support it.
await setupAttributes(
device,
coordinatorEndpoint,
'genOnOff',
[{attribute: 'startUpOnOff', min: 'MIN', max: 'MAX', change: 1}],
false,
);
} catch (e) {
if (e.message.includes('UNSUPPORTED_ATTRIBUTE')) {
logger.debug('Reading startUpOnOff failed, this features is unsupported', 'zhc:onoff');
} else {
throw e;
}
}
}
},
configureSetPowerSourceWhenUnknown('Mains (single phase)'),
];
}
return result;
}
export interface CommandsOnOffArgs {
commands?: ('on' | 'off' | 'toggle')[];
bind?: boolean;
endpointNames?: string[];
}
export function commandsOnOff(args?: CommandsOnOffArgs): ModernExtend {
args = {commands: ['on', 'off', 'toggle'], bind: true, ...args};
let actions: string[] = args.commands;
if (args.endpointNames) {
actions = args.commands.map((c) => args.endpointNames.map((e) => `${c}_${e}`)).flat();
}
const exposes: Expose[] = [e.enum('action', ea.STATE, actions).withDescription('Triggered action (e.g. a button click)')];
const actionPayloadLookup: KeyValueString = {
commandOn: 'on',
commandOff: 'off',
commandOffWithEffect: 'off',
commandToggle: 'toggle',
};
const fromZigbee: Fz.Converter[] = [
{
cluster: 'genOnOff',
type: ['commandOn', 'commandOff', 'commandOffWithEffect', 'commandToggle'],
convert: (model, msg, publish, options, meta) => {
if (hasAlreadyProcessedMessage(msg, model)) return;
const payload = {action: postfixWithEndpointName(actionPayloadLookup[msg.type], msg, model, meta)};
addActionGroup(payload, msg, model);
return payload;
},
},
];
const result: ModernExtend = {exposes, fromZigbee, isModernExtend: true};
if (args.bind) result.configure = [setupConfigureForBinding('genOnOff', 'output', args.endpointNames)];
return result;
}
export function customTimeResponse(start: '1970_UTC' | '2000_LOCAL'): ModernExtend {
// The Zigbee Cluster Library specification states that the genTime.time response should be the
// number of seconds since 1st Jan 2000 00:00:00 UTC. This extend modifies that:
// 1970_UTC: number of seconds since the Unix Epoch (1st Jan 1970 00:00:00 UTC)
// 2000_LOCAL: seconds since 1 January in the local time zone.
// Disable the responses of zigbee-herdsman and respond here instead.
const onEvent: OnEvent = async (type, data, device, options, state: KeyValue) => {
if (!device.customReadResponse) {
device.customReadResponse = (frame, endpoint) => {
if (frame.isCluster('genTime')) {
const payload: KeyValue = {};
if (start === '1970_UTC') {
const time = Math.round(new Date().getTime() / 1000);
payload.time = time;
payload.localTime = time - new Date().getTimezoneOffset() * 60;
} else if (start === '2000_LOCAL') {
const oneJanuary2000 = new Date('January 01, 2000 00:00:00 UTC+00:00').getTime();
const secondsUTC = Math.round((new Date().getTime() - oneJanuary2000) / 1000);
payload.time = secondsUTC - new Date().getTimezoneOffset() * 60;
}
endpoint.readResponse('genTime', frame.header.transactionSequenceNumber, payload).catch((e) => {
logger.warning(`Custom time response failed for '${device.ieeeAddr}': ${e}`, 'zhc:customtimeresponse');
});
return true;
}
return false;
};
}
};
return {onEvent, isModernExtend: true};
}
// #endregion
// #region Measurement and Sensing
export function illuminance(args?: Partial<NumericArgs>): ModernExtend {
const luxScale: ScaleFunction = (value: number, type: 'from' | 'to') => {
let result = value;
if (type === 'from') {
result = Math.pow(10, (result - 1) / 10000);
}
return result;
};
const result = numeric({
name: 'illuminance',
cluster: 'msIlluminanceMeasurement',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 5}, // 5 lux
description: 'Measured illuminance',
unit: 'lx',
scale: luxScale,
access: 'STATE_GET',
...args,
});
const fzIlluminanceRaw = {
cluster: 'msIlluminanceMeasurement',
type: ['attributeReport', 'readResponse'],
options: [opt.illuminance_raw()],
convert: (model, msg, publish, options, meta) => {
if (options.illuminance_raw) {
return {illuminance_raw: msg.data['measuredValue']};
}
},
} satisfies Fz.Converter;
result.fromZigbee.push(fzIlluminanceRaw);
const exposeIlluminanceRaw: DefinitionExposes = (device, options) => {
return options?.illuminance_raw ? [e.illuminance_raw()] : [];
};
result.exposes.push(exposeIlluminanceRaw);
return result;
}
export function temperature(args?: Partial<NumericArgs>) {
return numeric({
name: 'temperature',
cluster: 'msTemperatureMeasurement',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 100},
description: 'Measured temperature value',
unit: '°C',
scale: 100,
access: 'STATE_GET',
...args,
});
}
export function pressure(args?: Partial<NumericArgs>): ModernExtend {
return numeric({
name: 'pressure',
cluster: 'msPressureMeasurement',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 50}, // 5 kPa
description: 'The measured atmospheric pressure',
unit: 'kPa',
scale: 10,
access: 'STATE_GET',
...args,
});
}
export function flow(args?: Partial<NumericArgs>) {
return numeric({
name: 'flow',
cluster: 'msFlowMeasurement',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 10},
description: 'Measured water flow',
unit: 'm³/h',
scale: 10,
access: 'STATE_GET',
...args,
});
}
export function humidity(args?: Partial<NumericArgs>) {
return numeric({
name: 'humidity',
cluster: 'msRelativeHumidity',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 100},
description: 'Measured relative humidity',
unit: '%',
scale: 100,
access: 'STATE_GET',
...args,
});
}
export function soilMoisture(args?: Partial<NumericArgs>) {
return numeric({
name: 'soil_moisture',
cluster: 'msSoilMoisture',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 100},
description: 'Measured soil moisture value',
unit: '%',
scale: 100,
access: 'STATE_GET',
...args,
});
}
export interface OccupancyArgs {
pirConfig?: ('otu_delay' | 'uto_delay' | 'uto_threshold')[];
ultrasonicConfig?: ('otu_delay' | 'uto_delay' | 'uto_threshold')[];
contactConfig?: ('otu_delay' | 'uto_delay' | 'uto_threshold')[];
reporting?: boolean;
reportingConfig?: ReportingConfigWithoutAttribute;
endpointNames?: string[];
}
export function occupancy(args?: OccupancyArgs): ModernExtend {
args = {reporting: true, reportingConfig: {min: '10_SECONDS', max: '1_MINUTE', change: 0}, ...args};
const templateExposes: Expose[] = [e.occupancy().withAccess(ea.STATE_GET)];
const exposes: (Expose | DefinitionExposesFunction)[] = args.endpointNames
? templateExposes.map((exp) => args.endpointNames.map((ep) => exp.withEndpoint(ep))).flat()
: templateExposes;
const fromZigbee: Fz.Converter[] = [
{
cluster: 'msOccupancySensing',
type: ['attributeReport', 'readResponse'],
options: [opt.no_occupancy_since_false()],
convert: (model, msg, publish, options, meta) => {
if ('occupancy' in msg.data && (!args.endpointNames || args.endpointNames.includes(getEndpointName(msg, model, meta).toString()))) {
const propertyName = postfixWithEndpointName('occupancy', msg, model, meta);
const payload = {[propertyName]: (msg.data['occupancy'] & 1) > 0};
noOccupancySince(msg.endpoint, options, publish, payload[propertyName] ? 'stop' : 'start');
return payload;
}
},
},
];
const toZigbee: Tz.Converter[] = [
{
key: ['occupancy'],
convertGet: async (entity, key, meta) => {
await determineEndpoint(entity, meta, 'msOccupancySensing').read('msOccupancySensing', ['occupancy']);
},
},
];
const settingsExtends: ModernExtend[] = [];
const settingsTemplate = {
cluster: 'msOccupancySensing',
description: '',
endpointNames: args.endpointNames,
access: 'ALL' as 'STATE' | 'STATE_GET' | 'ALL',
entityCategory: 'config' as 'config' | 'diagnostic',
};
const attributesForReading: string[] = [];
if (args.pirConfig) {
if (args.pirConfig.includes('otu_delay')) {
settingsExtends.push(
numeric({
name: 'occupancy_timeout',
attribute: 'pirOToUDelay',
valueMin: 0,
valueMax: 65534,
unit: 's',
...settingsTemplate,
description: 'Time in seconds before occupancy is cleared after the last detected movement.',
}),
);
attributesForReading.push('pirOToUDelay');
}
if (args.pirConfig.includes('uto_delay')) {
settingsExtends.push(
numeric({
name: 'pir_uto_delay',
attribute: 'pirUToODelay',
valueMin: 0,
valueMax: 65534,
...settingsTemplate,
}),
);
attributesForReading.push('pirUToODelay');
}
if (args.pirConfig.includes('uto_threshold')) {
settingsExtends.push(
numeric({
name: 'pir_uto_threshold',
attribute: 'pirUToOThreshold',
valueMin: 1,
valueMax: 254,
...settingsTemplate,
}),
);
attributesForReading.push('pirUToOThreshold');
}
}
if (args.ultrasonicConfig) {
if (args.pirConfig.includes('otu_delay')) {
settingsExtends.push(
numeric({
name: 'ultrasonic_otu_delay',
attribute: 'ultrasonicOToUDelay',
valueMin: 0,
valueMax: 65534,
...settingsTemplate,
}),
);
attributesForReading.push('ultrasonicOToUDelay');
}
if (args.pirConfig.includes('uto_delay')) {
settingsExtends.push(
numeric({
name: 'ultrasonic_uto_delay',
attribute: 'ultrasonicUToODelay',
valueMin: 0,
valueMax: 65534,
...settingsTemplate,
}),
);
attributesForReading.push('ultrasonicUToODelay');
}
if (args.pirConfig.includes('uto_threshold')) {
settingsExtends.push(
numeric({
name: 'ultrasonic_uto_threshold',
attribute: 'ultrasonicUToOThreshold',
valueMin: 1,
valueMax: 254,
...settingsTemplate,
}),
);
attributesForReading.push('ultrasonicUToOThreshold');
}
}
if (args.contactConfig) {
if (args.pirConfig.includes('otu_delay')) {
settingsExtends.push(
numeric({
name: 'contact_otu_delay',
attribute: 'contactOToUDelay',
valueMin: 0,
valueMax: 65534,
...settingsTemplate,
}),
);
attributesForReading.push('contactOToUDelay');
}
if (args.pirConfig.includes('uto_delay')) {
settingsExtends.push(
numeric({
name: 'contact_uto_delay',
attribute: 'contactUToODelay',
valueMin: 0,
valueMax: 65534,
...settingsTemplate,
}),
);
attributesForReading.push('contactUToODelay');
}
if (args.pirConfig.includes('uto_threshold')) {
settingsExtends.push(
numeric({
name: 'contact_uto_threshold',
attribute: 'contactUToOThreshold',
valueMin: 1,
valueMax: 254,
...settingsTemplate,
}),
);
attributesForReading.push('contactUToOThreshold');
}
}
settingsExtends.map((extend) => exposes.push(...extend.exposes));
settingsExtends.map((extend) => fromZigbee.push(...extend.fromZigbee));
settingsExtends.map((extend) => toZigbee.push(...extend.toZigbee));
const configure: Configure[] = [];
if (attributesForReading.length > 0) configure.push(setupConfigureForReading('msOccupancySensing', attributesForReading, args.endpointNames));
if (args.reporting) {
configure.push(setupConfigureForReporting('msOccupancySensing', 'occupancy', args.reportingConfig, ea.STATE_GET, args.endpointNames));
}
return {exposes, fromZigbee, toZigbee, configure, isModernExtend: true};
}
export function co2(args?: Partial<NumericArgs>) {
return numeric({
name: 'co2',
cluster: 'msCO2',
label: 'CO2',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 0.00005}, // 50 ppm change
description: 'Measured value',
unit: 'ppm',
scale: 0.000001,
access: 'STATE_GET',
...args,
});
}
export function pm25(args?: Partial<NumericArgs>): ModernExtend {
return numeric({
name: 'pm25',
cluster: 'pm25Measurement',
attribute: 'measuredValue',
reporting: {min: '10_SECONDS', max: '1_HOUR', change: 1},
description: 'Measured PM2.5 (particulate matter) concentration',
unit: 'µg/m³',
access: 'STATE_GET',
...args,
});
}
// #endregion
// #region Lighting
export interface LightArgs {
effect?: boolean;
powerOnBehavior?: boolean;
colorTemp?: {startup?: boolean; range: Range};
color?: boolean | {modes?: ('xy' | 'hs')[]; applyRedFix?: boolean; enhancedHue?: boolean};
turnsOffAtBrightness1?: boolean;
configureReporting?: boolean;
endpointNames?: string[];
ota?: ModernExtend['ota'];
levelConfig?: {disabledFeatures?: string[]};
}
export function light(args?: LightArgs): ModernExtend {
args = {effect: true, powerOnBehavior: true, configureReporting: false, ...args};
if (args.colorTemp) {
args.colorTemp = {startup: true, ...args.colorTemp};
}
const argsColor = args.color
? {
modes: ['xy'] satisfies ('xy' | 'hs')[],
applyRedFix: false,
enhancedHue: true,
...(isObject(args.color) ? args.color : {}),
}
: false;
const lightExpose = exposeEndpoints(e.light().withBrightness(), args.endpointNames);