-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
tuya.ts
2590 lines (2451 loc) · 115 KB
/
tuya.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 fz from '../converters/fromZigbee';
import tz from '../converters/toZigbee';
import * as constants from './constants';
import * as exposes from './exposes';
import {logger} from './logger';
import * as modernExtend from './modernExtend';
import * as globalStore from './store';
import {
DefinitionExposesFunction,
Expose,
Fz,
KeyValue,
KeyValueAny,
KeyValueNumberString,
ModernExtend,
OnEvent,
OnEventData,
OnEventType,
Publish,
Range,
Tuya,
Tz,
Zh,
} from './types';
import * as utils from './utils';
import {configureSetPowerSourceWhenUnknown} from './utils';
// import {Color} from './color';
const NS = 'zhc:tuya';
const e = exposes.presets;
const ea = exposes.access;
interface KeyValueStringEnum {
[s: string]: Enum;
}
export const dataTypes = {
raw: 0, // [ bytes ]
bool: 1, // [0/1]
number: 2, // [ 4 byte value ]
string: 3, // [ N byte string ]
enum: 4, // [ 0-255 ]
bitmap: 5, // [ 1,2,4 bytes ] as bits
};
export function convertBufferToNumber(chunks: Buffer | number[]) {
let value = 0;
for (let i = 0; i < chunks.length; i++) {
value = value << 8;
value += chunks[i];
}
return value;
}
function convertStringToHexArray(value: string) {
const asciiKeys = [];
for (let i = 0; i < value.length; i++) {
asciiKeys.push(value[i].charCodeAt(0));
}
return asciiKeys;
}
interface OnEventArgs {
queryOnDeviceAnnounce?: boolean;
timeStart?: '1970' | '2000';
respondToMcuVersionResponse?: boolean;
queryIntervalSeconds?: number;
}
export function onEvent(args?: OnEventArgs): OnEvent {
return async (type, data, device, settings, state) => {
args = {queryOnDeviceAnnounce: false, timeStart: '1970', respondToMcuVersionResponse: true, ...args};
const endpoint = device.endpoints[0];
if (type === 'message' && data.cluster === 'manuSpecificTuya') {
if (args.respondToMcuVersionResponse && data.type === 'commandMcuVersionResponse') {
await endpoint.command('manuSpecificTuya', 'mcuVersionRequest', {seq: 0x0002});
} else if (data.type === 'commandMcuGatewayConnectionStatus') {
// "payload" can have the following values:
// 0x00: The gateway is not connected to the internet.
// 0x01: The gateway is connected to the internet.
// 0x02: The request timed out after three seconds.
const payload = {payloadSize: 1, payload: 1};
await endpoint.command('manuSpecificTuya', 'mcuGatewayConnectionStatus', payload, {});
}
}
if (data.type === 'commandMcuSyncTime' && data.cluster === 'manuSpecificTuya') {
try {
const offset = args.timeStart === '2000' ? constants.OneJanuary2000 : 0;
const utcTime = Math.round((new Date().getTime() - offset) / 1000);
const localTime = utcTime - new Date().getTimezoneOffset() * 60;
const payload = {
payloadSize: 8,
payload: [...convertDecimalValueTo4ByteHexArray(utcTime), ...convertDecimalValueTo4ByteHexArray(localTime)],
};
await endpoint.command('manuSpecificTuya', 'mcuSyncTime', payload, {});
} catch {
/* handle error to prevent crash */
}
}
// Some devices require a dataQuery on deviceAnnounce, otherwise they don't report any data
if (args.queryOnDeviceAnnounce && type === 'deviceAnnounce') {
await endpoint.command('manuSpecificTuya', 'dataQuery', {});
}
if (args.queryIntervalSeconds) {
if (type === 'stop') {
clearTimeout(globalStore.getValue(device, 'query_interval'));
globalStore.clearValue(device, 'query_interval');
} else if (!globalStore.hasValue(device, 'query_interval')) {
const setTimer = () => {
const timer = setTimeout(async () => {
try {
await endpoint.command('manuSpecificTuya', 'dataQuery', {});
} catch {
/* Do nothing*/
}
setTimer();
}, args.queryIntervalSeconds * 1000);
globalStore.putValue(device, 'query_interval', timer);
};
setTimer();
}
}
};
}
function getDataValue(dpValue: Tuya.DpValue) {
let dataString = '';
switch (dpValue.datatype) {
case dataTypes.raw:
return dpValue.data;
case dataTypes.bool:
return dpValue.data[0] === 1;
case dataTypes.number:
return convertBufferToNumber(dpValue.data);
case dataTypes.string:
// Don't use .map here, doesn't work: https://github.com/Koenkk/zigbee-herdsman-converters/pull/1799/files#r530377091
for (let i = 0; i < dpValue.data.length; ++i) {
dataString += String.fromCharCode(dpValue.data[i]);
}
return dataString;
case dataTypes.enum:
return dpValue.data[0];
case dataTypes.bitmap:
return convertBufferToNumber(dpValue.data);
}
}
export function convertDecimalValueTo4ByteHexArray(value: number) {
const hexValue = Number(value).toString(16).padStart(8, '0');
const chunk1 = hexValue.substring(0, 2);
const chunk2 = hexValue.substring(2, 4);
const chunk3 = hexValue.substring(4, 6);
const chunk4 = hexValue.substring(6);
return [chunk1, chunk2, chunk3, chunk4].map((hexVal) => parseInt(hexVal, 16));
}
function convertDecimalValueTo2ByteHexArray(value: number) {
const hexValue = Number(value).toString(16).padStart(4, '0');
const chunk1 = hexValue.substring(0, 2);
const chunk2 = hexValue.substring(2);
return [chunk1, chunk2].map((hexVal) => parseInt(hexVal, 16));
}
export async function onEventMeasurementPoll(
type: OnEventType,
data: OnEventData,
device: Zh.Device,
options: KeyValue,
electricalMeasurement = true,
metering = false,
) {
const endpoint = device.getEndpoint(1);
const poll = async () => {
if (electricalMeasurement) {
await endpoint.read('haElectricalMeasurement', ['rmsVoltage', 'rmsCurrent', 'activePower']);
}
if (metering) {
await endpoint.read('seMetering', ['currentSummDelivered']);
}
};
utils.onEventPoll(type, data, device, options, 'measurement', 60, poll);
}
export async function onEventSetTime(type: OnEventType, data: KeyValue, device: Zh.Device) {
// FIXME: Need to join onEventSetTime/onEventSetLocalTime to one command
if (data.type === 'commandMcuSyncTime' && data.cluster === 'manuSpecificTuya') {
try {
const utcTime = Math.round((new Date().getTime() - constants.OneJanuary2000) / 1000);
const localTime = utcTime - new Date().getTimezoneOffset() * 60;
const endpoint = device.getEndpoint(1);
const payload = {
payloadSize: 8,
payload: [...convertDecimalValueTo4ByteHexArray(utcTime), ...convertDecimalValueTo4ByteHexArray(localTime)],
};
await endpoint.command('manuSpecificTuya', 'mcuSyncTime', payload, {});
} catch {
// endpoint.command can throw an error which needs to
// be caught or the zigbee-herdsman may crash
// Debug message is handled in the zigbee-herdsman
}
}
}
// set UTC and Local Time as total number of seconds from 00: 00: 00 on January 01, 1970
// force to update every device time every hour due to very poor clock
export async function onEventSetLocalTime(type: OnEventType, data: KeyValue, device: Zh.Device) {
// FIXME: What actually nextLocalTimeUpdate/forceTimeUpdate do?
// I did not find any timers or something else where it was used.
// Actually, there are two ways to set time on Tuya MCU devices:
// 1. Respond to the `commandMcuSyncTime` event
// 2. Just send `mcuSyncTime` anytime (by 1-hour timer or something else)
const nextLocalTimeUpdate = globalStore.getValue(device, 'nextLocalTimeUpdate');
const forceTimeUpdate = nextLocalTimeUpdate == null || nextLocalTimeUpdate < new Date().getTime();
if ((data.type === 'commandMcuSyncTime' && data.cluster === 'manuSpecificTuya') || forceTimeUpdate) {
globalStore.putValue(device, 'nextLocalTimeUpdate', new Date().getTime() + 3600 * 1000);
try {
const utcTime = Math.round(new Date().getTime() / 1000);
const localTime = utcTime - new Date().getTimezoneOffset() * 60;
const endpoint = device.getEndpoint(1);
const payload = {
payloadSize: 8,
payload: [...convertDecimalValueTo4ByteHexArray(utcTime), ...convertDecimalValueTo4ByteHexArray(localTime)],
};
await endpoint.command('manuSpecificTuya', 'mcuSyncTime', payload, {});
} catch {
// endpoint.command can throw an error which needs to
// be caught or the zigbee-herdsman may crash
// Debug message is handled in the zigbee-herdsman
}
}
}
// Return `seq` - transaction ID for handling concrete response
async function sendDataPoints(entity: Zh.Endpoint | Zh.Group, dpValues: Tuya.DpValue[], cmd = 'dataRequest', seq?: number) {
if (seq === undefined) {
seq = globalStore.getValue(entity, 'sequence', 0);
globalStore.putValue(entity, 'sequence', (seq + 1) % 0xffff);
}
await entity.command('manuSpecificTuya', cmd, {seq, dpValues}, {disableDefaultResponse: true});
return seq;
}
function dpValueFromNumberValue(dp: number, value: number) {
return {dp, datatype: dataTypes.number, data: convertDecimalValueTo4ByteHexArray(value)};
}
function dpValueFromBool(dp: number, value: boolean) {
return {dp, datatype: dataTypes.bool, data: [value ? 1 : 0]};
}
function dpValueFromEnum(dp: number, value: number) {
return {dp, datatype: dataTypes.enum, data: [value]};
}
function dpValueFromString(dp: number, string: string) {
return {dp, datatype: dataTypes.string, data: convertStringToHexArray(string)};
}
function dpValueFromRaw(dp: number, rawBuffer: number[]) {
return {dp, datatype: dataTypes.raw, data: rawBuffer};
}
function dpValueFromBitmap(dp: number, bitmapBuffer: number) {
return {dp, datatype: dataTypes.bitmap, data: [bitmapBuffer]};
}
export async function sendDataPointValue(entity: Zh.Group | Zh.Endpoint, dp: number, value: number, cmd?: string, seq?: number) {
return await sendDataPoints(entity, [dpValueFromNumberValue(dp, value)], cmd, seq);
}
export async function sendDataPointBool(entity: Zh.Group | Zh.Endpoint, dp: number, value: boolean, cmd?: string, seq?: number) {
return await sendDataPoints(entity, [dpValueFromBool(dp, value)], cmd, seq);
}
export async function sendDataPointEnum(entity: Zh.Group | Zh.Endpoint, dp: number, value: number, cmd?: string, seq?: number) {
return await sendDataPoints(entity, [dpValueFromEnum(dp, value)], cmd, seq);
}
export async function sendDataPointRaw(entity: Zh.Group | Zh.Endpoint, dp: number, value: number[], cmd?: string, seq?: number) {
return await sendDataPoints(entity, [dpValueFromRaw(dp, value)], cmd, seq);
}
export async function sendDataPointBitmap(entity: Zh.Group | Zh.Endpoint, dp: number, value: number, cmd?: string, seq?: number) {
return await sendDataPoints(entity, [dpValueFromBitmap(dp, value)], cmd, seq);
}
export async function sendDataPointStringBuffer(entity: Zh.Group | Zh.Endpoint, dp: number, value: string, cmd?: string, seq?: number) {
return await sendDataPoints(entity, [dpValueFromString(dp, value)], cmd, seq);
}
const tuyaExposes = {
lightType: () => e.enum('light_type', ea.STATE_SET, ['led', 'incandescent', 'halogen']).withDescription('Type of light attached to the device'),
lightBrightnessWithMinMax: () =>
e
.light_brightness()
.withMinBrightness()
.withMaxBrightness()
.setAccess('state', ea.STATE_SET)
.setAccess('brightness', ea.STATE_SET)
.setAccess('min_brightness', ea.STATE_SET)
.setAccess('max_brightness', ea.STATE_SET),
lightBrightness: () => e.light_brightness().setAccess('state', ea.STATE_SET).setAccess('brightness', ea.STATE_SET),
countdown: () =>
e
.numeric('countdown', ea.STATE_SET)
.withValueMin(0)
.withValueMax(43200)
.withValueStep(1)
.withUnit('s')
.withDescription('Countdown to turn device off after a certain time'),
switch: () => e.switch().setAccess('state', ea.STATE_SET),
selfTest: () => e.binary('self_test', ea.STATE_SET, true, false).withDescription('Indicates whether the device is being self-tested'),
selfTestResult: () =>
e.enum('self_test_result', ea.STATE, ['checking', 'success', 'failure', 'others']).withDescription('Result of the self-test'),
faultAlarm: () => e.binary('fault_alarm', ea.STATE, true, false).withDescription('Indicates whether a fault was detected'),
silence: () => e.binary('silence', ea.STATE_SET, true, false).withDescription('Silence the alarm'),
frostProtection: (extraNote = '') =>
e
.binary('frost_protection', ea.STATE_SET, 'ON', 'OFF')
.withDescription(`When Anti-Freezing function is activated, the temperature in the house is kept at 8 °C.${extraNote}`),
errorStatus: () => e.numeric('error_status', ea.STATE).withDescription('Error status'),
scheduleAllDays: (access: number, format: string) =>
['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map((day) =>
e.text(`schedule_${day}`, access).withDescription(`Schedule for ${day}, format: "${format}"`),
),
temperatureUnit: () => e.enum('temperature_unit', ea.STATE_SET, ['celsius', 'fahrenheit']).withDescription('Temperature unit'),
temperatureCalibration: () =>
e
.numeric('temperature_calibration', ea.STATE_SET)
.withValueMin(-2.0)
.withValueMax(2.0)
.withValueStep(0.1)
.withUnit('°C')
.withDescription('Temperature calibration'),
humidityCalibration: () =>
e
.numeric('humidity_calibration', ea.STATE_SET)
.withValueMin(-30)
.withValueMax(30)
.withValueStep(1)
.withUnit('%')
.withDescription('Humidity calibration'),
gasValue: () => e.numeric('gas_value', ea.STATE).withDescription('Measured gas concentration'),
energyWithPhase: (phase: string) =>
e.numeric(`energy_${phase}`, ea.STATE).withUnit('kWh').withDescription(`Sum of consumed energy (phase ${phase.toUpperCase()})`),
energyProducedWithPhase: (phase: string) =>
e.numeric(`energy_produced_${phase}`, ea.STATE).withUnit('kWh').withDescription(`Sum of produced energy (phase ${phase.toUpperCase()})`),
energyFlowWithPhase: (phase: string, more: [string]) =>
e
.enum(`energy_flow_${phase}`, ea.STATE, ['consuming', 'producing', ...more])
.withDescription(`Direction of energy (phase ${phase.toUpperCase()})`),
voltageWithPhase: (phase: string) =>
e.numeric(`voltage_${phase}`, ea.STATE).withUnit('V').withDescription(`Measured electrical potential value (phase ${phase.toUpperCase()})`),
powerWithPhase: (phase: string) =>
e.numeric(`power_${phase}`, ea.STATE).withUnit('W').withDescription(`Instantaneous measured power (phase ${phase.toUpperCase()})`),
currentWithPhase: (phase: string) =>
e
.numeric(`current_${phase}`, ea.STATE)
.withUnit('A')
.withDescription(`Instantaneous measured electrical current (phase ${phase.toUpperCase()})`),
powerFactorWithPhase: (phase: string) =>
e
.numeric(`power_factor_${phase}`, ea.STATE)
.withUnit('%')
.withDescription(`Instantaneous measured power factor (phase ${phase.toUpperCase()})`),
switchType: () => e.enum('switch_type', ea.ALL, ['toggle', 'state', 'momentary']).withDescription('Type of the switch'),
backlightModeLowMediumHigh: () => e.enum('backlight_mode', ea.ALL, ['low', 'medium', 'high']).withDescription('Intensity of the backlight'),
backlightModeOffNormalInverted: () => e.enum('backlight_mode', ea.ALL, ['off', 'normal', 'inverted']).withDescription('Mode of the backlight'),
backlightModeOffOn: () => e.binary('backlight_mode', ea.ALL, 'ON', 'OFF').withDescription(`Mode of the backlight`),
indicatorMode: () => e.enum('indicator_mode', ea.ALL, ['off', 'off/on', 'on/off', 'on']).withDescription('LED indicator mode'),
indicatorModeNoneRelayPos: () => e.enum('indicator_mode', ea.ALL, ['none', 'relay', 'pos']).withDescription('Mode of the indicator light'),
powerOutageMemory: () => e.enum('power_outage_memory', ea.ALL, ['on', 'off', 'restore']).withDescription('Recover state after power outage'),
batteryState: () => e.enum('battery_state', ea.STATE, ['low', 'medium', 'high']).withDescription('State of the battery'),
doNotDisturb: () =>
e
.binary('do_not_disturb', ea.STATE_SET, true, false)
.withDescription('Do not disturb mode, when enabled this function will keep the light OFF after a power outage'),
colorPowerOnBehavior: () =>
e.enum('color_power_on_behavior', ea.STATE_SET, ['initial', 'previous', 'customized']).withDescription('Power on behavior state'),
switchMode: () =>
e.enum('switch_mode', ea.STATE_SET, ['switch', 'scene']).withDescription('Sets the mode of the switch to act as a switch or as a scene'),
switchMode2: () =>
e
.enum('switch_mode', ea.STATE_SET, ['switch', 'curtain'])
.withDescription('Sets the mode of the switch to act as a switch or as a curtain controller'),
lightMode: () =>
e.enum('light_mode', ea.STATE_SET, ['normal', 'on', 'off', 'flash']).withDescription(`'Sets the indicator mode of l1.
Normal: Orange while off and white while on.
On: Always white. Off: Always orange.
Flash: Flashes white when triggered.
Note: Orange light will turn off after light off delay, white light always stays on. Light mode updates on next state change.'`),
// Inching can be enabled for multiple endpoints (1 to 6) but it is always controlled on endpoint 1
// So instead of pinning the values to each endpoint, it is easier to keep the structure stand alone.
inchingSwitch: (quantity: number) => {
const x = e
.composite('inching_control_set', 'inching_control_set', ea.SET)
.withDescription(
'Device Inching function Settings. The device will automatically turn off ' + 'after each turn on for a specified period of time.',
);
for (let i = 1; i <= quantity; i++) {
x.withFeature(
e
.binary('inching_control', ea.SET, 'ENABLE', 'DISABLE')
.withDescription('Enable/disable inching function for endpoint ' + i + '.')
.withLabel('Inching for Endpoint ' + i)
.withProperty('inching_control_' + i),
).withFeature(
e
.numeric('inching_time', ea.SET)
.withDescription('Delay time for executing a inching action for endpoint ' + i + '.')
.withLabel('Inching time for endpoint ' + i)
.withProperty('inching_time_' + i)
.withUnit('seconds')
.withValueMin(1)
.withValueMax(65535)
.withValueStep(1),
);
}
return x;
},
};
export {tuyaExposes as exposes};
export const skip = {
// Prevent state from being published when already ON and brightness is also published.
// This prevents 100% -> X% brightness jumps when the switch is already on
// https://github.com/Koenkk/zigbee2mqtt/issues/13800#issuecomment-1263592783
stateOnAndBrightnessPresent: (meta: Tz.Meta) => {
if (Array.isArray(meta.mapped)) throw new Error('Not supported');
const convertedKey = meta.mapped.meta.multiEndpoint && meta.endpoint_name ? `state_${meta.endpoint_name}` : 'state';
return meta.message.brightness !== undefined && meta.state[convertedKey] === meta.message.state;
},
};
export const configureMagicPacket = async (device: Zh.Device, coordinatorEndpoint: Zh.Endpoint) => {
try {
const endpoint = device.endpoints[0];
await endpoint.read('genBasic', ['manufacturerName', 'zclVersion', 'appVersion', 'modelId', 'powerSource', 0xfffe]);
} catch (e) {
// Fails for some Tuya devices with UNSUPPORTED_ATTRIBUTE, ignore that.
// e.g. https://github.com/Koenkk/zigbee2mqtt/issues/14857
if (e.message.includes('UNSUPPORTED_ATTRIBUTE')) {
logger.debug('configureMagicPacket failed, ignoring...', NS);
} else {
throw e;
}
}
};
export const fingerprint = (modelID: string, manufacturerNames: string[]) => {
return manufacturerNames.map((manufacturerName) => {
return {modelID, manufacturerName};
});
};
export const whitelabel = (vendor: string, model: string, description: string, manufacturerNames: string[]) => {
const fingerprint = manufacturerNames.map((manufacturerName) => {
return {manufacturerName};
});
return {vendor, model, description, fingerprint};
};
class Base {
value: number;
constructor(value: number) {
this.value = value;
}
valueOf() {
return this.value;
}
}
export class Enum extends Base {
constructor(value: number) {
super(value);
}
}
const enumConstructor = (value: number) => new Enum(value);
export {enumConstructor as enum};
export class Bitmap extends Base {
constructor(value: number) {
super(value);
}
}
type LookupMap = {[s: string]: number | boolean | Enum | string};
export const valueConverterBasic = {
lookup: (map: LookupMap | ((options: KeyValue, device: Zh.Device) => LookupMap), fallbackValue?: number | boolean | KeyValue | string | null) => {
return {
to: (v: string, meta: Tz.Meta) => utils.getFromLookup(v, typeof map === 'function' ? map(meta.options, meta.device) : map),
from: (v: number, _meta: Fz.Meta, options: KeyValue) => {
const m = typeof map === 'function' ? map(options, _meta.device) : map;
const value = Object.entries(m).find((i) => i[1].valueOf() === v);
if (!value) {
if (fallbackValue !== undefined) return fallbackValue;
throw new Error(`Value '${v}' is not allowed, expected one of ${Object.values(m).map((i) => i.valueOf())}`);
}
return value[0];
},
};
},
scale: (min1: number, max1: number, min2: number, max2: number) => {
return {
to: (v: number) => utils.mapNumberRange(v, min1, max1, min2, max2),
from: (v: number) => utils.mapNumberRange(v, min2, max2, min1, max1),
};
},
raw: () => {
return {to: (v: string | number | boolean) => v, from: (v: string | number | boolean) => v};
},
divideBy: (value: number) => {
return {to: (v: number) => v * value, from: (v: number) => v / value};
},
divideByFromOnly: (value: number) => {
return {to: (v: number) => v, from: (v: number) => v / value};
},
trueFalse: (valueTrue: number | Enum) => {
return {from: (v: number) => v === valueTrue.valueOf()};
},
};
export const valueConverter = {
trueFalse0: valueConverterBasic.trueFalse(0),
trueFalse1: valueConverterBasic.trueFalse(1),
trueFalseInvert: {
to: (v: boolean) => !v,
from: (v: boolean) => !v,
},
trueFalseEnum0: valueConverterBasic.trueFalse(new Enum(0)),
trueFalseEnum1: valueConverterBasic.trueFalse(new Enum(1)),
onOff: valueConverterBasic.lookup({ON: true, OFF: false}),
powerOnBehavior: valueConverterBasic.lookup({off: 0, on: 1, previous: 2}),
powerOnBehaviorEnum: valueConverterBasic.lookup({off: new Enum(0), on: new Enum(1), previous: new Enum(2)}),
switchType: valueConverterBasic.lookup({momentary: new Enum(0), toggle: new Enum(1), state: new Enum(2)}),
switchType2: valueConverterBasic.lookup({toggle: new Enum(0), state: new Enum(1), momentary: new Enum(2)}),
backlightModeOffNormalInverted: valueConverterBasic.lookup({off: new Enum(0), normal: new Enum(1), inverted: new Enum(2)}),
backlightModeOffLowMediumHigh: valueConverterBasic.lookup({off: new Enum(0), low: new Enum(1), medium: new Enum(2), high: new Enum(3)}),
lightType: valueConverterBasic.lookup({led: 0, incandescent: 1, halogen: 2}),
countdown: valueConverterBasic.raw(),
scale0_254to0_1000: valueConverterBasic.scale(0, 254, 0, 1000),
scale0_1to0_1000: valueConverterBasic.scale(0, 1, 0, 1000),
temperatureUnit: valueConverterBasic.lookup({celsius: 0, fahrenheit: 1}),
temperatureUnitEnum: valueConverterBasic.lookup({celsius: new Enum(0), fahrenheit: new Enum(1)}),
batteryState: valueConverterBasic.lookup({low: 0, medium: 1, high: 2}),
divideBy2: valueConverterBasic.divideBy(2),
divideBy10: valueConverterBasic.divideBy(10),
divideBy100: valueConverterBasic.divideBy(100),
divideBy1000: valueConverterBasic.divideBy(1000),
divideBy10FromOnly: valueConverterBasic.divideByFromOnly(10),
switchMode: valueConverterBasic.lookup({switch: new Enum(0), scene: new Enum(1)}),
switchMode2: valueConverterBasic.lookup({switch: new Enum(0), curtain: new Enum(1)}),
lightMode: valueConverterBasic.lookup({normal: new Enum(0), on: new Enum(1), off: new Enum(2), flash: new Enum(3)}),
raw: valueConverterBasic.raw(),
localTemperatureCalibration: {
from: (value: number) => (value > 4000 ? value - 4096 : value),
to: (value: number) => (value < 0 ? 4096 + value : value),
},
setLimit: {
to: (v: number) => {
if (!v) throw new Error('Limit cannot be unset, use factory_reset');
return v;
},
from: (v: number) => v,
},
coverPosition: {
to: async (v: number, meta: Tz.Meta) => {
return meta.options.invert_cover ? 100 - v : v;
},
from: (v: number, meta: Fz.Meta, options: KeyValue, publish: Publish) => {
const position = options.invert_cover ? 100 - v : v;
publish({state: position === 0 ? 'CLOSE' : 'OPEN'});
return position;
},
},
coverPositionInverted: {
to: async (v: number, meta: Tz.Meta) => {
return meta.options.invert_cover ? v : 100 - v;
},
from: (v: number, meta: Fz.Meta, options: KeyValue, publish: Publish) => {
const position = options.invert_cover ? v : 100 - v;
publish({state: position === 0 ? 'CLOSE' : 'OPEN'});
return position;
},
},
tubularMotorDirection: valueConverterBasic.lookup({normal: new Enum(0), reversed: new Enum(1)}),
plus1: {
from: (v: number) => v + 1,
to: (v: number) => v - 1,
},
static: (value: string | number) => {
return {
from: (v: string | number) => {
return value;
},
};
},
phaseVariant1: {
from: (v: string) => {
const buffer = Buffer.from(v, 'base64');
return {voltage: (buffer[14] | (buffer[13] << 8)) / 10, current: (buffer[12] | (buffer[11] << 8)) / 1000};
},
},
phaseVariant2: {
from: (v: string) => {
const buf = Buffer.from(v, 'base64');
return {voltage: (buf[1] | (buf[0] << 8)) / 10, current: (buf[4] | (buf[3] << 8)) / 1000, power: buf[7] | (buf[6] << 8)};
},
},
phaseVariant2WithPhase: (phase: string) => {
return {
from: (v: string) => {
// Support negative power readings
// https://github.com/Koenkk/zigbee2mqtt/issues/18603#issuecomment-2277697295
const buf = Buffer.from(v, 'base64');
let power = buf[7] | (buf[6] << 8);
if (power > 0x7fff) {
power = (0x999a - power) * -1;
}
return {
[`voltage_${phase}`]: (buf[1] | (buf[0] << 8)) / 10,
[`current_${phase}`]: (buf[4] | (buf[3] << 8)) / 1000,
[`power_${phase}`]: power,
};
},
};
},
phaseVariant3: {
from: (v: string) => {
const buf = Buffer.from(v, 'base64');
return {
voltage: ((buf[0] << 8) | buf[1]) / 10,
current: ((buf[2] << 16) | (buf[3] << 8) | buf[4]) / 1000,
power: (buf[5] << 16) | (buf[6] << 8) | buf[7],
};
},
},
power: {
from: (v: number) => {
// Support negative readings
// https://github.com/Koenkk/zigbee2mqtt/issues/18603
return v > 0x0fffffff ? (0x1999999c - v) * -1 : v;
},
},
threshold: {
from: (v: string) => {
const buffer = Buffer.from(v, 'base64');
const stateLookup: KeyValue = {0: 'not_set', 1: 'over_current_threshold', 3: 'over_voltage_threshold'};
const protectionLookup: KeyValue = {0: 'OFF', 1: 'ON'};
return {
threshold_1_protection: protectionLookup[buffer[1]],
threshold_1: stateLookup[buffer[0]],
threshold_1_value: buffer[3] | (buffer[2] << 8),
threshold_2_protection: protectionLookup[buffer[5]],
threshold_2: stateLookup[buffer[4]],
threshold_2_value: buffer[7] | (buffer[6] << 8),
};
},
},
threshold_2: {
to: async (v: number, meta: Tz.Meta) => {
const entity = meta.device.endpoints[0];
const onOffLookup = {on: 1, off: 0};
const sendCommand = utils.getMetaValue(entity, meta.mapped, 'tuyaSendCommand', undefined, 'dataRequest');
if (meta.message.overload_breaker) {
const threshold = meta.state['overload_threshold'];
const buf = Buffer.from([
3,
utils.getFromLookup(meta.message.overload_breaker, onOffLookup),
0,
utils.toNumber(threshold, 'overload_threshold'),
]);
await sendDataPointRaw(entity, 17, Array.from(buf), sendCommand, 1);
} else if (meta.message.overload_threshold) {
const state = meta.state['overload_breaker'];
const buf = Buffer.from([
3,
utils.getFromLookup(state, onOffLookup),
0,
utils.toNumber(meta.message.overload_threshold, 'overload_threshold'),
]);
await sendDataPointRaw(entity, 17, Array.from(buf), sendCommand, 1);
} else if (meta.message.leakage_threshold) {
const state = meta.state['leakage_breaker'];
const buf = Buffer.alloc(8);
buf.writeUInt8(4, 4);
buf.writeUInt8(utils.getFromLookup(state, onOffLookup), 5);
buf.writeUInt16BE(utils.toNumber(meta.message.leakage_threshold, 'leakage_threshold'), 6);
await sendDataPointRaw(entity, 17, Array.from(buf), sendCommand, 1);
} else if (meta.message.leakage_breaker) {
const threshold = meta.state['leakage_threshold'];
const buf = Buffer.alloc(8);
buf.writeUInt8(4, 4);
buf.writeUInt8(utils.getFromLookup(meta.message.leakage_breaker, onOffLookup), 5);
buf.writeUInt16BE(utils.toNumber(threshold, 'leakage_threshold'), 6);
await sendDataPointRaw(entity, 17, Array.from(buf), sendCommand, 1);
} else if (meta.message.high_temperature_threshold) {
const state = meta.state['high_temperature_breaker'];
const buf = Buffer.alloc(12);
buf.writeUInt8(5, 8);
buf.writeUInt8(utils.getFromLookup(state, onOffLookup), 9);
buf.writeUInt16BE(utils.toNumber(meta.message.high_temperature_threshold, 'high_temperature_threshold'), 10);
await sendDataPointRaw(entity, 17, Array.from(buf), sendCommand, 1);
} else if (meta.message.high_temperature_breaker) {
const threshold = meta.state['high_temperature_threshold'];
const buf = Buffer.alloc(12);
buf.writeUInt8(5, 8);
buf.writeUInt8(utils.getFromLookup(meta.message.high_temperature_breaker, onOffLookup), 9);
buf.writeUInt16BE(utils.toNumber(threshold, 'high_temperature_threshold'), 10);
await sendDataPointRaw(entity, 17, Array.from(buf), sendCommand, 1);
}
},
from: (v: string) => {
const data = Buffer.from(v, 'base64');
const result: KeyValue = {};
const lookup: KeyValue = {0: 'OFF', 1: 'ON'};
const alarmLookup: KeyValue = {3: 'overload', 4: 'leakage', 5: 'high_temperature'};
const len = data.length;
let i = 0;
while (i < len) {
if (Object.prototype.hasOwnProperty.call(alarmLookup, data[i])) {
const alarm = alarmLookup[data[i]];
const state = lookup[data[i + 1]];
const threshold = data[i + 3] | (data[i + 2] << 8);
result[`${alarm}_breaker`] = state;
result[`${alarm}_threshold`] = threshold;
}
i += 4;
}
return result;
},
},
threshold_3: {
to: async (v: number, meta: Tz.Meta) => {
const entity = meta.device.endpoints[0];
const onOffLookup = {on: 1, off: 0};
const sendCommand = utils.getMetaValue(entity, meta.mapped, 'tuyaSendCommand', undefined, 'dataRequest');
if (meta.message.over_current_threshold) {
const state = meta.state['over_current_breaker'];
const buf = Buffer.from([
1,
utils.getFromLookup(state, onOffLookup),
0,
utils.toNumber(meta.message.over_current_threshold, 'over_current_threshold'),
]);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.over_current_breaker) {
const threshold = meta.state['over_current_threshold'];
const buf = Buffer.from([
1,
utils.getFromLookup(meta.message.over_current_breaker, onOffLookup),
0,
utils.toNumber(threshold, 'over_current_threshold'),
]);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.over_voltage_threshold) {
const state = meta.state['over_voltage_breaker'];
const buf = Buffer.alloc(8);
buf.writeUInt8(3, 4);
buf.writeUInt8(utils.getFromLookup(state, onOffLookup), 5);
buf.writeUInt16BE(utils.toNumber(meta.message.over_voltage_threshold, 'over_voltage_threshold'), 6);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.over_voltage_breaker) {
const threshold = meta.state['over_voltage_threshold'];
const buf = Buffer.alloc(8);
buf.writeUInt8(3, 4);
buf.writeUInt8(utils.getFromLookup(meta.message.over_voltage_breaker, onOffLookup), 5);
buf.writeUInt16BE(utils.toNumber(threshold, 'over_voltage_threshold'), 6);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.under_voltage_threshold) {
const state = meta.state['under_voltage_breaker'];
const buf = Buffer.alloc(12);
buf.writeUInt8(4, 8);
buf.writeUInt8(utils.getFromLookup(state, onOffLookup), 9);
buf.writeUInt16BE(utils.toNumber(meta.message.under_voltage_threshold, 'under_voltage_threshold'), 10);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.under_voltage_breaker) {
const threshold = meta.state['under_voltage_threshold'];
const buf = Buffer.alloc(12);
buf.writeUInt8(4, 8);
buf.writeUInt8(utils.getFromLookup(meta.message.under_voltage_breaker, onOffLookup), 9);
buf.writeUInt16BE(utils.toNumber(threshold, 'under_voltage_threshold'), 10);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.insufficient_balance_threshold) {
const state = meta.state['insufficient_balance_breaker'];
const buf = Buffer.alloc(16);
buf.writeUInt8(8, 12);
buf.writeUInt8(utils.getFromLookup(state, onOffLookup), 13);
buf.writeUInt16BE(utils.toNumber(meta.message.insufficient_balance_threshold, 'insufficient_balance_threshold'), 14);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
} else if (meta.message.insufficient_balance_breaker) {
const threshold = meta.state['insufficient_balance_threshold'];
const buf = Buffer.alloc(16);
buf.writeUInt8(8, 12);
buf.writeUInt8(utils.getFromLookup(meta.message.insufficient_balance_breaker, onOffLookup), 13);
buf.writeUInt16BE(utils.toNumber(threshold, 'insufficient_balance_threshold'), 14);
await sendDataPointRaw(entity, 18, Array.from(buf), sendCommand, 1);
}
},
from: (v: string) => {
const data = Buffer.from(v, 'base64');
const result: KeyValue = {};
const lookup: KeyValue = {0: 'OFF', 1: 'ON'};
const alarmLookup: KeyValue = {1: 'over_current', 3: 'over_voltage', 4: 'under_voltage', 8: 'insufficient_balance'};
const len = data.length;
let i = 0;
while (i < len) {
if (Object.prototype.hasOwnProperty.call(alarmLookup, data[i])) {
const alarm = alarmLookup[data[i]];
const state = lookup[data[i + 1]];
const threshold = data[i + 3] | (data[i + 2] << 8);
result[`${alarm}_breaker`] = state;
result[`${alarm}_threshold`] = threshold;
}
i += 4;
}
return result;
},
},
selfTestResult: valueConverterBasic.lookup({checking: 0, success: 1, failure: 2, others: 3}),
lockUnlock: valueConverterBasic.lookup({LOCK: true, UNLOCK: false}),
localTempCalibration1: {
from: (v: number) => {
if (v > 55) v -= 0x100000000;
return v / 10;
},
to: (v: number) => {
if (v > 0) return v * 10;
if (v < 0) return v * 10 + 0x100000000;
return v;
},
},
localTempCalibration2: {
from: (v: number) => v,
to: (v: number) => {
if (v < 0) return v + 0x100000000;
return v;
},
},
localTempCalibration3: {
from: (v: number) => {
if (v > 0x7fffffff) v -= 0x100000000;
return v / 10;
},
to: (v: number) => {
if (v > 0) return v * 10;
if (v < 0) return v * 10 + 0x100000000;
return v;
},
},
thermostatHolidayStartStop: {
from: (v: string) => {
const start = {
year: v.slice(0, 4),
month: v.slice(4, 6),
day: v.slice(6, 8),
hours: v.slice(8, 10),
minutes: v.slice(10, 12),
};
const end = {
year: v.slice(12, 16),
month: v.slice(16, 18),
day: v.slice(18, 20),
hours: v.slice(20, 22),
minutes: v.slice(22, 24),
};
const startStr = `${start.year}/${start.month}/${start.day} ${start.hours}:${start.minutes}`;
const endStr = `${end.year}/${end.month}/${end.day} ${end.hours}:${end.minutes}`;
return `${startStr} | ${endStr}`;
},
to: (v: string) => {
const numberPattern = /\d+/g;
// @ts-expect-error ignore
return v.match(numberPattern).join([]).toString();
},
},
thermostatScheduleDaySingleDP: {
from: (v: number[]) => {
// day split to 10 min segments = total 144 segments
const maxPeriodsInDay = 10;
const periodSize = 3;
const schedule = [];
for (let i = 0; i < maxPeriodsInDay; i++) {
const time = v[i * periodSize];
const totalMinutes = time * 10;
const hours = totalMinutes / 60;
const rHours = Math.floor(hours);
const minutes = (hours - rHours) * 60;
const rMinutes = Math.round(minutes);
const strHours = rHours.toString().padStart(2, '0');
const strMinutes = rMinutes.toString().padStart(2, '0');
const tempHexArray = [v[i * periodSize + 1], v[i * periodSize + 2]];
const tempRaw = Buffer.from(tempHexArray).readUIntBE(0, tempHexArray.length);
const temp = tempRaw / 10;
schedule.push(`${strHours}:${strMinutes}/${temp}`);
if (rHours === 24) break;
}
return schedule.join(' ');
},
to: (v: KeyValue, meta: Tz.Meta) => {
const dayByte: KeyValue = {
monday: 1,
tuesday: 2,
wednesday: 4,
thursday: 8,
friday: 16,
saturday: 32,
sunday: 64,
};
const weekDay = v.week_day;
utils.assertString(weekDay, 'week_day');
if (Object.keys(dayByte).indexOf(weekDay) === -1) {
throw new Error('Invalid "week_day" property value: ' + weekDay);
}
let weekScheduleType = 'separate';
if (meta.state && meta.state.working_day) {
weekScheduleType = String(meta.state.working_day);
}
const payload = [];
switch (weekScheduleType) {
case 'mon_sun':
payload.push(127);
break;
case 'mon_fri+sat+sun':
if (['saturday', 'sunday'].indexOf(weekDay) === -1) {
payload.push(31);
break;
}
payload.push(dayByte[weekDay]);
break;
case 'separate':
payload.push(dayByte[weekDay]);
break;
default:
throw new Error('Invalid "working_day" property, need to set it before');
}
// day split to 10 min segments = total 144 segments
const maxPeriodsInDay = 10;
utils.assertString(v.schedule, 'schedule');
const schedule = v.schedule.split(' ');
const schedulePeriods = schedule.length;
if (schedulePeriods > 10) throw new Error('There cannot be more than 10 periods in the schedule: ' + v);
if (schedulePeriods < 2) throw new Error('There cannot be less than 2 periods in the schedule: ' + v);
let prevHour;
for (const period of schedule) {
const timeTemp = period.split('/');
const hm = timeTemp[0].split(':', 2);
const h = parseInt(hm[0]);
const m = parseInt(hm[1]);
const temp = parseFloat(timeTemp[1]);
if (h < 0 || h > 24 || m < 0 || m >= 60 || m % 10 !== 0 || temp < 5 || temp > 30 || temp % 0.5 !== 0) {
throw new Error('Invalid hour, minute or temperature of: ' + period);
} else if (prevHour > h) {
throw new Error(`The hour of the next segment can't be less than the previous one: ${prevHour} > ${h}`);
}
prevHour = h;
const segment = (h * 60 + m) / 10;
const tempHexArray = convertDecimalValueTo2ByteHexArray(temp * 10);
payload.push(segment, ...tempHexArray);
}
// Add "technical" periods to be valid payload
for (let i = 0; i < maxPeriodsInDay - schedulePeriods; i++) {
// by default it sends 9000b2, it's 24 hours and 18 degrees
payload.push(144, 0, 180);
}
return payload;
},
},
thermostatScheduleDayMultiDP: {
from: (v: string) => valueConverter.thermostatScheduleDayMultiDPWithTransitionCount().from(v),
to: (v: string) => valueConverter.thermostatScheduleDayMultiDPWithTransitionCount().to(v),