-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathtuya.js
5326 lines (5290 loc) · 276 KB
/
tuya.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const exposes = require('../lib/exposes');
const fz = {...require('../converters/fromZigbee'), legacy: require('../lib/legacy').fromZigbee};
const tz = require('../converters/toZigbee');
const ota = require('../lib/ota');
const tuya = require('../lib/tuya');
const reporting = require('../lib/reporting');
const extend = require('../lib/extend');
const e = exposes.presets;
const ea = exposes.access;
const libColor = require('../lib/color');
const utils = require('../lib/utils');
const zosung = require('../lib/zosung');
const fzZosung = zosung.fzZosung;
const tzZosung = zosung.tzZosung;
const ez = zosung.presetsZosung;
const globalStore = require('../lib/store');
const {ColorMode, colorModeLookup} = require('../lib/constants');
const tzLocal = {
led_control: {
key: ['brightness', 'color', 'color_temp', 'transition'],
options: [exposes.options.color_sync()],
convertSet: async (entity, _key, _value, meta) => {
const newState = {};
// The color mode encodes whether the light is using its white LEDs or its color LEDs
let colorMode = meta.state.color_mode ?? colorModeLookup[ColorMode.ColorTemp];
// Color mode switching is done by setting color temperature (switch to white LEDs) or setting color (switch
// to color LEDs)
if ('color_temp' in meta.message) colorMode = colorModeLookup[ColorMode.ColorTemp];
if ('color' in meta.message) colorMode = colorModeLookup[ColorMode.HS];
if (colorMode != meta.state.color_mode) {
newState.color_mode = colorMode;
// To switch between white mode and color mode, we have to send a special command:
const rgbMode = (colorMode == colorModeLookup[ColorMode.HS]);
await entity.command('lightingColorCtrl', 'tuyaRgbMode', {enable: rgbMode}, {}, {disableDefaultResponse: true});
}
// A transition time of 0 would be treated as about 1 second, probably some kind of fallback/default
// transition time, so for "no transition" we use 1 (tenth of a second).
const transtime = 'transition' in meta.message ? meta.message.transition * 10 : 1;
if (colorMode == colorModeLookup[ColorMode.ColorTemp]) {
if ('brightness' in meta.message) {
const zclData = {level: Number(meta.message.brightness), transtime};
await entity.command('genLevelCtrl', 'moveToLevel', zclData, utils.getOptions(meta.mapped, entity));
newState.brightness = meta.message.brightness;
}
if ('color_temp' in meta.message) {
const zclData = {colortemp: meta.message.color_temp, transtime: transtime};
await entity.command('lightingColorCtrl', 'moveToColorTemp', zclData, utils.getOptions(meta.mapped, entity));
newState.color_temp = meta.message.color_temp;
}
} else if (colorMode == colorModeLookup[ColorMode.HS]) {
if ('brightness' in meta.message || 'color' in meta.message) {
// We ignore the brightness of the color and instead use the overall brightness setting of the lamp
// for the brightness because I think that's the expected behavior and also because the color
// conversion below always returns 100 as brightness ("value") even for very dark colors, except
// when the color is completely black/zero.
// Load current state or defaults
const newSettings = {
brightness: meta.state.brightness ?? 254, // full brightness
hue: (meta.state.color ?? {}).hue ?? 0, // red
saturation: (meta.state.color ?? {}).saturation ?? 100, // full saturation
};
// Apply changes
if ('brightness' in meta.message) {
newSettings.brightness = meta.message.brightness;
newState.brightness = meta.message.brightness;
}
if ('color' in meta.message) {
// The Z2M UI sends `{ hex:'#xxxxxx' }`.
// Home Assistant sends `{ h: xxx, s: xxx }`.
// We convert the former into the latter.
const c = libColor.Color.fromConverterArg(meta.message.color);
if (c.isRGB()) {
// https://github.com/Koenkk/zigbee2mqtt/issues/13421#issuecomment-1426044963
c.hsv = c.rgb.gammaCorrected().toXY().toHSV();
}
const color = c.hsv;
newSettings.hue = color.hue;
newSettings.saturation = color.saturation;
newState.color = {
hue: color.hue,
saturation: color.saturation,
};
}
// Convert to device specific format and send
const zclData = {
brightness: utils.mapNumberRange(newSettings.brightness, 0, 254, 0, 1000),
hue: newSettings.hue,
saturation: utils.mapNumberRange(newSettings.saturation, 0, 100, 0, 1000),
};
// This command doesn't support a transition time
await entity.command('lightingColorCtrl', 'tuyaMoveToHueAndSaturationBrightness2', zclData,
utils.getOptions(meta.mapped, entity));
}
}
// If we're in white mode, calculate a matching display color for the set color temperature. This also kind
// of works in the other direction.
Object.assign(newState, libColor.syncColorState(newState, meta.state, entity, meta.options, meta.logger));
return {state: newState};
},
convertGet: async (entity, key, meta) => {
await entity.read('lightingColorCtrl', ['currentHue', 'currentSaturation', 'currentLevel', 'tuyaRgbMode', 'colorTemperature']);
},
},
TS110E_options: {
key: ['min_brightness', 'max_brightness', 'light_type', 'switch_type'],
convertSet: async (entity, key, value, meta) => {
let payload = null;
if (key === 'min_brightness' || key == 'max_brightness') {
const id = key === 'min_brightness' ? 64515 : 64516;
payload = {[id]: {value: utils.mapNumberRange(value, 1, 255, 0, 1000), type: 0x21}};
} else if (key === 'light_type' || key === 'switch_type') {
const lookup = key === 'light_type' ? {led: 0, incandescent: 1, halogen: 2} : {momentary: 0, toggle: 1, state: 2};
payload = {64514: {value: lookup[value], type: 0x20}};
}
await entity.write('genLevelCtrl', payload, utils.getOptions(meta.mapped, entity));
return {state: {[key]: value}};
},
convertGet: async (entity, key, meta) => {
let id = null;
if (key === 'min_brightness') id = 64515;
if (key === 'max_brightness') id = 64516;
if (key === 'light_type' || key === 'switch_type') id = 64514;
await entity.read('genLevelCtrl', [id]);
},
},
TS110E_onoff_brightness: {
key: ['state', 'brightness'],
options: [],
convertSet: async (entity, key, value, meta) => {
const {message, state} = meta;
if (message.state === 'OFF' || (message.hasOwnProperty('state') && !message.hasOwnProperty('brightness'))) {
return await tz.on_off.convertSet(entity, key, value, meta);
} else if (message.hasOwnProperty('brightness')) {
// set brightness
if (state.state === 'OFF') {
await entity.command('genOnOff', 'on', {}, utils.getOptions(meta.mapped, entity));
}
const level = utils.mapNumberRange(message.brightness, 0, 254, 0, 1000);
await entity.command('genLevelCtrl', 'moveToLevelTuya', {level, transtime: 100}, utils.getOptions(meta.mapped, entity));
return {state: {state: 'ON', brightness: message.brightness}};
}
},
convertGet: async (entity, key, meta) => {
if (key === 'state') await tz.on_off.convertGet(entity, key, meta);
if (key === 'brightness') await entity.read('genLevelCtrl', [61440]);
},
},
TS110E_light_onoff_brightness: {
...tz.light_onoff_brightness,
convertSet: async (entity, key, value, meta) => {
const {message} = meta;
if (message.state === 'ON' || message.brightness > 1) {
// Does not turn off with physical press when turned on with just moveToLevelWithOnOff, required on before.
// https://github.com/Koenkk/zigbee2mqtt/issues/15902#issuecomment-1382848150
await entity.command('genOnOff', 'on', {}, utils.getOptions(meta.mapped, entity));
}
return tz.light_onoff_brightness.convertSet(entity, key, value, meta);
},
},
SA12IZL_silence_siren: {
key: ['silence_siren'],
convertSet: async (entity, key, value, meta) => {
await tuya.sendDataPointBool(entity, 16, value);
},
},
SA12IZL_alarm: {
key: ['alarm'],
convertSet: async (entity, key, value, meta) => {
await tuya.sendDataPointEnum(entity, 20, {true: 0, false: 1}[value]);
},
},
hpsz: {
key: ['led_state'],
convertSet: async (entity, key, value, meta) => {
await tuya.sendDataPointBool(entity, tuya.dataPoints.HPSZLEDState, value);
},
},
TS0504B_color: {
key: ['color'],
convertSet: async (entity, key, value, meta) => {
const color = libColor.Color.fromConverterArg(value);
console.log(color);
const enableWhite =
(color.isRGB() && (color.rgb.red === 1 && color.rgb.green === 1 && color.rgb.blue === 1)) ||
// Zigbee2MQTT frontend white value
(color.isXY() && (color.xy.x === 0.3125 || color.xy.y === 0.32894736842105265)) ||
// Home Assistant white color picker value
(color.isXY() && (color.xy.x === 0.323 || color.xy.y === 0.329));
if (enableWhite) {
await entity.command('lightingColorCtrl', 'tuyaRgbMode', {enable: false});
const newState = {color_mode: 'xy'};
if (color.isXY()) {
newState.color = color.xy;
} else {
newState.color = color.rgb.gammaCorrected().toXY().rounded(4);
}
return {state: libColor.syncColorState(newState, meta.state, entity, meta.options, meta.logger)};
} else {
return await tz.light_color.convertSet(entity, key, value, meta);
}
},
},
TS0224: {
key: ['light', 'duration', 'volume'],
convertSet: async (entity, key, value, meta) => {
if (key === 'light') {
await entity.command('genOnOff', value.toLowerCase() === 'on' ? 'on' : 'off', {}, utils.getOptions(meta.mapped, entity));
} else if (key === 'duration') {
await entity.write('ssIasWd', {'maxDuration': value}, utils.getOptions(meta.mapped, entity));
} else if (key === 'volume') {
const lookup = {'mute': 0, 'low': 10, 'medium': 30, 'high': 50};
value = value.toLowerCase();
utils.validateValue(value, Object.keys(lookup));
await entity.write('ssIasWd', {0x0002: {value: lookup[value], type: 0x0a}}, utils.getOptions(meta.mapped, entity));
}
return {state: {[key]: value}};
},
},
zb_sm_cover: {
key: ['state', 'position', 'reverse_direction', 'top_limit', 'bottom_limit', 'favorite_position', 'goto_positon', 'report'],
convertSet: async (entity, key, value, meta) => {
switch (key) {
case 'position': {
const invert = (meta.state) ? !meta.state.invert_cover : false;
value = invert ? 100 - value : value;
if (value >= 0 && value <= 100) {
await tuya.sendDataPointValue(entity, tuya.dataPoints.coverPosition, value);
} else {
throw new Error('TuYa_cover_control: Curtain motor position is out of range');
}
break;
}
case 'state': {
const stateEnums = tuya.getCoverStateEnums(meta.device.manufacturerName);
meta.logger.debug(`TuYa_cover_control: Using state enums for ${meta.device.manufacturerName}:
${JSON.stringify(stateEnums)}`);
value = value.toLowerCase();
switch (value) {
case 'close':
await tuya.sendDataPointEnum(entity, tuya.dataPoints.state, stateEnums.close);
break;
case 'open':
await tuya.sendDataPointEnum(entity, tuya.dataPoints.state, stateEnums.open);
break;
case 'stop':
await tuya.sendDataPointEnum(entity, tuya.dataPoints.state, stateEnums.stop);
break;
default:
throw new Error('TuYa_cover_control: Invalid command received');
}
break;
}
case 'reverse_direction': {
meta.logger.info(`Motor direction ${(value) ? 'reverse' : 'forward'}`);
await tuya.sendDataPointEnum(entity, tuya.dataPoints.motorDirection, (value) ? 1 : 0);
break;
}
case 'top_limit': {
await tuya.sendDataPointEnum(entity, 104, {'SET': 0, 'CLEAR': 1}[value]);
break;
}
case 'bottom_limit': {
await tuya.sendDataPointEnum(entity, 103, {'SET': 0, 'CLEAR': 1}[value]);
break;
}
case 'favorite_position': {
await tuya.sendDataPointValue(entity, 115, value);
break;
}
case 'goto_positon': {
if (value == 'FAVORITE') {
value = (meta.state) ? meta.state.favorite_position : null;
} else {
value = parseInt(value);
}
return tz.tuya_cover_control.convertSet(entity, 'position', value, meta);
}
case 'report': {
await tuya.sendDataPointBool(entity, 116, 0);
break;
}
}
},
},
x5h_thermostat: {
key: ['system_mode', 'current_heating_setpoint', 'sensor', 'brightness_state', 'sound', 'frost_protection', 'week', 'factory_reset',
'local_temperature_calibration', 'heating_temp_limit', 'deadzone_temperature', 'upper_temp', 'preset', 'child_lock',
'schedule'],
convertSet: async (entity, key, value, meta) => {
switch (key) {
case 'system_mode':
await tuya.sendDataPointBool(entity, tuya.dataPoints.x5hState, value === 'heat');
break;
case 'preset': {
value = value.toLowerCase();
const lookup = {manual: 0, program: 1};
utils.validateValue(value, Object.keys(lookup));
value = lookup[value];
await tuya.sendDataPointEnum(entity, tuya.dataPoints.x5hMode, value);
break;
}
case 'upper_temp':
if (value >= 35 && value <= 95) {
await tuya.sendDataPointValue(entity, tuya.dataPoints.x5hSetTempCeiling, value);
const setpoint = globalStore.getValue(entity, 'currentHeatingSetpoint', 20);
const setpointRaw = Math.round(setpoint * 10);
await new Promise((r) => setTimeout(r, 500));
await tuya.sendDataPointValue(entity, tuya.dataPoints.x5hSetTemp, setpointRaw);
} else {
throw new Error('Supported values are in range [35, 95]');
}
break;
case 'deadzone_temperature':
if (value >= 0.5 && value <= 9.5) {
value = Math.round(value * 10);
await tuya.sendDataPointValue(entity, tuya.dataPoints.x5hTempDiff, value);
} else {
throw new Error('Supported values are in range [0.5, 9.5]');
}
break;
case 'heating_temp_limit':
if (value >= 5 && value <= 60) {
await tuya.sendDataPointValue(entity, tuya.dataPoints.x5hProtectionTempLimit, value);
} else {
throw new Error('Supported values are in range [5, 60]');
}
break;
case 'local_temperature_calibration':
if (value >= -9.9 && value <= 9.9) {
value = Math.round(value * 10);
if (value < 0) {
value = 0xFFFFFFFF + value + 1;
}
await tuya.sendDataPointValue(entity, tuya.dataPoints.x5hTempCorrection, value);
} else {
throw new Error('Supported values are in range [-9.9, 9.9]');
}
break;
case 'factory_reset':
await tuya.sendDataPointBool(entity, tuya.dataPoints.x5hFactoryReset, value === 'ON');
break;
case 'week':
await tuya.sendDataPointEnum(entity, tuya.dataPoints.x5hWorkingDaySetting,
utils.getKey(tuya.thermostatWeekFormat, value, value, Number));
break;
case 'frost_protection':
await tuya.sendDataPointBool(entity, tuya.dataPoints.x5hFrostProtection, value === 'ON');
break;
case 'sound':
await tuya.sendDataPointBool(entity, tuya.dataPoints.x5hSound, value === 'ON');
break;
case 'brightness_state': {
value = value.toLowerCase();
const lookup = {off: 0, low: 1, medium: 2, high: 3};
utils.validateValue(value, Object.keys(lookup));
value = lookup[value];
await tuya.sendDataPointEnum(entity, tuya.dataPoints.x5hBackplaneBrightness, value);
break;
}
case 'sensor': {
value = value.toLowerCase();
const lookup = {'internal': 0, 'external': 1, 'both': 2};
utils.validateValue(value, Object.keys(lookup));
value = lookup[value];
await tuya.sendDataPointEnum(entity, tuya.dataPoints.x5hSensorSelection, value);
break;
}
case 'current_heating_setpoint':
if (value >= 5 && value <= 60) {
value = Math.round(value * 10);
await tuya.sendDataPointValue(entity, tuya.dataPoints.x5hSetTemp, value);
} else {
throw new Error(`Unsupported value: ${value}`);
}
break;
case 'child_lock':
await tuya.sendDataPointBool(entity, tuya.dataPoints.x5hChildLock, value === 'LOCK');
break;
case 'schedule': {
const periods = value.split(' ');
const periodsNumber = 8;
const payload = [];
for (let i = 0; i < periodsNumber; i++) {
const timeTemp = periods[i].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 || temp < 5 || temp > 60) {
throw new Error('Invalid hour, minute or temperature of: ' + periods[i]);
}
const tempHexArray = tuya.convertDecimalValueTo2ByteHexArray(Math.round(temp * 10));
// 1 byte for hour, 1 byte for minutes, 2 bytes for temperature
payload.push(h, m, ...tempHexArray);
}
await tuya.sendDataPointRaw(entity, tuya.dataPoints.x5hWeeklyProcedure, payload);
break;
}
default:
break;
}
},
},
temperature_unit: {
key: ['temperature_unit'],
convertSet: async (entity, key, value, meta) => {
switch (key) {
case 'temperature_unit': {
await entity.write('manuSpecificTuya_2', {'57355': {value: {'celsius': 0, 'fahrenheit': 1}[value], type: 48}});
break;
}
default: // Unknown key
meta.logger.warn(`Unhandled key ${key}`);
}
},
},
TS011F_threshold: {
key: [
'temperature_threshold', 'temperature_breaker', 'power_threshold', 'power_breaker',
'over_current_threshold', 'over_current_breaker', 'over_voltage_threshold', 'over_voltage_breaker',
'under_voltage_threshold', 'under_voltage_breaker',
],
convertSet: async (entity, key, value, meta) => {
switch (key) {
case 'temperature_threshold': {
const state = meta.state['temperature_breaker'];
const buf = Buffer.from([5, {'ON': 1, 'OFF': 0}[state], 0, value]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'temperature_breaker': {
const threshold = meta.state['temperature_threshold'];
const buf = Buffer.from([5, {'ON': 1, 'OFF': 0}[value], 0, threshold]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'power_threshold': {
const state = meta.state['power_breaker'];
const buf = Buffer.from([7, {'ON': 1, 'OFF': 0}[state], 0, value]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'power_breaker': {
const threshold = meta.state['power_threshold'];
const buf = Buffer.from([7, {'ON': 1, 'OFF': 0}[value], 0, threshold]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'over_current_threshold': {
const state = meta.state['over_current_breaker'];
const buf = Buffer.from([1, {'ON': 1, 'OFF': 0}[state], 0, value]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'over_current_breaker': {
const threshold = meta.state['over_current_threshold'];
const buf = Buffer.from([1, {'ON': 1, 'OFF': 0}[value], 0, threshold]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'over_voltage_threshold': {
const state = meta.state['over_voltage_breaker'];
const buf = Buffer.from([3, {'ON': 1, 'OFF': 0}[state], 0, value]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'over_voltage_breaker': {
const threshold = meta.state['over_voltage_threshold'];
const buf = Buffer.from([3, {'ON': 1, 'OFF': 0}[value], 0, threshold]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'under_voltage_threshold': {
const state = meta.state['under_voltage_breaker'];
const buf = Buffer.from([4, {'ON': 1, 'OFF': 0}[state], 0, value]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'under_voltage_breaker': {
const threshold = meta.state['under_voltage_threshold'];
const buf = Buffer.from([4, {'ON': 1, 'OFF': 0}[value], 0, threshold]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
default: // Unknown key
meta.logger.warn(`Unhandled key ${key}`);
}
},
},
};
const fzLocal = {
TS0222_humidity: {
...fz.humidity,
convert: (model, msg, publish, options, meta) => {
const result = fz.humidity.convert(model, msg, publish, options, meta);
result.humidity *= 10;
return result;
},
},
TS110E: {
cluster: 'genLevelCtrl',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const result = {};
if (msg.data.hasOwnProperty('64515')) {
result['min_brightness'] = utils.mapNumberRange(msg.data['64515'], 0, 1000, 1, 255);
}
if (msg.data.hasOwnProperty('64516')) {
result['max_brightness'] = utils.mapNumberRange(msg.data['64516'], 0, 1000, 1, 255);
}
if (msg.data.hasOwnProperty('61440')) {
result['brightness'] = utils.mapNumberRange(msg.data['61440'], 0, 1000, 0, 255);
}
return result;
},
},
TS110E_light_type: {
cluster: 'genLevelCtrl',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const result = {};
if (msg.data.hasOwnProperty('64514')) {
const lookup = {0: 'led', 1: 'incandescent', 2: 'halogen'};
result['light_type'] = lookup[msg.data['64514']];
}
return result;
},
},
TS110E_switch_type: {
cluster: 'genLevelCtrl',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const result = {};
if (msg.data.hasOwnProperty('64514')) {
const lookup = {0: 'momentary', 1: 'toggle', 2: 'state'};
const propertyName = utils.postfixWithEndpointName('switch_type', msg, model, meta);
result[propertyName] = lookup[msg.data['64514']];
}
return result;
},
},
SA12IZL: {
cluster: 'manuSpecificTuya',
type: ['commandDataResponse', 'commandDataReport'],
convert: (model, msg, publish, options, meta) => {
const result = {};
for (const dpValue of msg.data.dpValues) {
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
switch (dp) {
case tuya.dataPoints.state:
result.smoke = value === 0;
break;
case 15:
result.battery = value;
break;
case 16:
result.silence_siren = value;
break;
case 20: {
const alarm = {0: true, 1: false};
result.alarm = alarm[value];
break;
}
default:
meta.logger.debug(`zigbee-herdsman-converters:SA12IZL: NOT RECOGNIZED DP #${
dp} with data ${JSON.stringify(dpValue)}`);
}
}
return result;
},
},
tuya_dinrail_switch2: {
cluster: 'manuSpecificTuya',
type: ['commandDataReport', 'commandDataResponse', 'commandActiveStatusReport'],
convert: (model, msg, publish, options, meta) => {
const dpValue = tuya.firstDpValue(msg, meta, 'tuya_dinrail_switch2');
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
const state = value ? 'ON' : 'OFF';
switch (dp) {
case tuya.dataPoints.state: // DPID that we added to common
return {state: state};
case tuya.dataPoints.dinrailPowerMeterTotalEnergy2:
return {energy: value/100};
case tuya.dataPoints.dinrailPowerMeterPower2:
return {power: value};
default:
meta.logger.debug(`zigbee-herdsman-converters:TuyaDinRailSwitch: NOT RECOGNIZED DP ` +
`#${dp} with data ${JSON.stringify(dpValue)}`);
}
},
},
hpsz: {
cluster: 'manuSpecificTuya',
type: ['commandDataResponse', 'commandDataReport'],
convert: (model, msg, publish, options, meta) => {
const dpValue = tuya.firstDpValue(msg, meta, 'hpsz');
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
let result = null;
switch (dp) {
case tuya.dataPoints.HPSZInductionState:
result = {presence: value === 1};
break;
case tuya.dataPoints.HPSZPresenceTime:
result = {duration_of_attendance: value};
break;
case tuya.dataPoints.HPSZLeavingTime:
result = {duration_of_absence: value};
break;
case tuya.dataPoints.HPSZLEDState:
result = {led_state: value};
break;
default:
meta.logger.debug(`zigbee-herdsman-converters:hpsz: NOT RECOGNIZED DP #${
dp} with data ${JSON.stringify(dpValue)}`);
}
return result;
},
},
scenes_recall_scene_65029: {
cluster: '65029',
type: ['raw', 'attributeReport'],
convert: (model, msg, publish, options, meta) => {
const id = meta.device.modelID === '005f0c3b' ? msg.data[0] : msg.data[msg.data.length - 1];
return {action: `scene_${id}`};
},
},
TS0201_battery: {
cluster: 'genPowerCfg',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
// https://github.com/Koenkk/zigbee2mqtt/issues/11470
if (msg.data.batteryPercentageRemaining == 200 && msg.data.batteryVoltage < 30) return;
return fz.battery.convert(model, msg, publish, options, meta);
},
},
TS0201_humidity: {
...fz.humidity,
convert: (model, msg, publish, options, meta) => {
if (meta.device.manufacturerName === '_TZ3000_ywagc4rj') {
msg.data['measuredValue'] *= 10;
}
return fz.humidity.convert(model, msg, publish, options, meta);
},
},
TS0222: {
cluster: 'manuSpecificTuya',
type: ['commandDataResponse', 'commandDataReport'],
convert: (model, msg, publish, options, meta) => {
const result = {};
for (const dpValue of msg.data.dpValues) {
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
switch (dp) {
case 2:
result.illuminance = value;
result.illuminance_lux = value;
break;
case 4:
result.battery = value;
break;
default:
meta.logger.warn(`zigbee-herdsman-converters:TS0222 Unrecognized DP #${dp} with data ${JSON.stringify(dpValue)}`);
}
}
return result;
},
},
ZM35HQ_battery: {
cluster: 'manuSpecificTuya',
type: ['commandDataReport'],
convert: (model, msg, publish, options, meta) => {
const dpValue = tuya.firstDpValue(msg, meta, 'ZM35HQ');
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
if (dp === 4) return {battery: value};
else {
meta.logger.debug(`zigbee-herdsman-converters:ZM35HQ: NOT RECOGNIZED DP #${dp} with data ${JSON.stringify(dpValue)}`);
}
},
},
zb_sm_cover: {
cluster: 'manuSpecificTuya',
type: ['commandDataReport', 'commandDataResponse'],
convert: (model, msg, publish, options, meta) => {
const result = {};
for (const dpValue of msg.data.dpValues) {
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
switch (dp) {
case tuya.dataPoints.coverPosition: // Started moving to position (triggered from Zigbee)
case tuya.dataPoints.coverArrived: { // Arrived at position
const invert = (meta.state) ? !meta.state.invert_cover : false;
const position = invert ? 100 - (value & 0xFF) : (value & 0xFF);
if (position > 0 && position <= 100) {
result.position = position;
result.state = 'OPEN';
} else if (position == 0) { // Report fully closed
result.position = position;
result.state = 'CLOSE';
}
break;
}
case 1: // report state
result.state = {0: 'OPEN', 1: 'STOP', 2: 'CLOSE'}[value];
break;
case tuya.dataPoints.motorDirection: // reverse direction
result.reverse_direction = (value == 1);
break;
case 10: // cycle time
result.cycle_time = value;
break;
case 101: // model
result.motor_type = {0: '', 1: 'AM0/6-28R-Sm', 2: 'AM0/10-19R-Sm',
3: 'AM1/10-13R-Sm', 4: 'AM1/20-13R-Sm', 5: 'AM1/30-13R-Sm'}[value];
break;
case 102: // cycles
result.cycle_count = value;
break;
case 103: // set or clear bottom limit
result.bottom_limit = {0: 'SET', 1: 'CLEAR'}[value];
break;
case 104: // set or clear top limit
result.top_limit = {0: 'SET', 1: 'CLEAR'}[value];
break;
case 109: // active power
result.active_power = value;
break;
case 115: // favorite_position
result.favorite_position = (value != 101) ? value : null;
break;
case 116: // report confirmation
break;
case 121: // running state
result.motor_state = {0: 'OPENING', 1: 'STOPPED', 2: 'CLOSING'}[value];
result.running = (value !== 1) ? true : false;
break;
default: // Unknown code
meta.logger.debug(`zb_sm_tuya_cover: Unhandled DP #${dp} for ${meta.device.manufacturerName}:
${JSON.stringify(dpValue)}`);
}
}
return result;
},
},
x5h_thermostat: {
cluster: 'manuSpecificTuya',
type: ['commandDataResponse', 'commandDataReport'],
convert: (model, msg, publish, options, meta) => {
const dpValue = tuya.firstDpValue(msg, meta, 'x5h_thermostat');
const dp = dpValue.dp;
const value = tuya.getDataValue(dpValue);
switch (dp) {
case tuya.dataPoints.x5hState: {
return {system_mode: value ? 'heat' : 'off'};
}
case tuya.dataPoints.x5hWorkingStatus: {
return {running_state: value ? 'heat' : 'idle'};
}
case tuya.dataPoints.x5hSound: {
return {sound: value ? 'ON' : 'OFF'};
}
case tuya.dataPoints.x5hFrostProtection: {
return {frost_protection: value ? 'ON' : 'OFF'};
}
case tuya.dataPoints.x5hWorkingDaySetting: {
return {week: tuya.thermostatWeekFormat[value]};
}
case tuya.dataPoints.x5hFactoryReset: {
if (value) {
clearTimeout(globalStore.getValue(msg.endpoint, 'factoryResetTimer'));
const timer = setTimeout(() => publish({factory_reset: 'OFF'}), 60 * 1000);
globalStore.putValue(msg.endpoint, 'factoryResetTimer', timer);
meta.logger.info('The thermostat is resetting now. It will be available in 1 minute.');
}
return {factory_reset: value ? 'ON' : 'OFF'};
}
case tuya.dataPoints.x5hTempDiff: {
return {deadzone_temperature: parseFloat((value / 10).toFixed(1))};
}
case tuya.dataPoints.x5hProtectionTempLimit: {
return {heating_temp_limit: value};
}
case tuya.dataPoints.x5hBackplaneBrightness: {
const lookup = {0: 'off', 1: 'low', 2: 'medium', 3: 'high'};
if (value >= 0 && value <= 3) {
globalStore.putValue(msg.endpoint, 'brightnessState', value);
return {brightness_state: lookup[value]};
}
// Sometimes, for example on thermostat restart, it sends message like:
// {"dpValues":[{"data":{"data":[90],"type":"Buffer"},"datatype":4,"dp":104}
// It doesn't represent any brightness value and brightness remains the previous value
const lastValue = globalStore.getValue(msg.endpoint, 'brightnessState') || 1;
return {brightness_state: lookup[lastValue]};
}
case tuya.dataPoints.x5hWeeklyProcedure: {
const periods = [];
const periodSize = 4;
const periodsNumber = 8;
for (let i = 0; i < periodsNumber; i++) {
const hours = value[i * periodSize];
const minutes = value[i * periodSize + 1];
const tempHexArray = [value[i * periodSize + 2], value[i * periodSize + 3]];
const tempRaw = Buffer.from(tempHexArray).readUIntBE(0, tempHexArray.length);
const strHours = hours.toString().padStart(2, '0');
const strMinutes = minutes.toString().padStart(2, '0');
const temp = parseFloat((tempRaw / 10).toFixed(1));
periods.push(`${strHours}:${strMinutes}/${temp}`);
}
const schedule = periods.join(' ');
return {schedule};
}
case tuya.dataPoints.x5hChildLock: {
return {child_lock: value ? 'LOCK' : 'UNLOCK'};
}
case tuya.dataPoints.x5hSetTemp: {
const setpoint = parseFloat((value / 10).toFixed(1));
globalStore.putValue(msg.endpoint, 'currentHeatingSetpoint', setpoint);
return {current_heating_setpoint: setpoint};
}
case tuya.dataPoints.x5hSetTempCeiling: {
return {upper_temp: value};
}
case tuya.dataPoints.x5hCurrentTemp: {
const temperature = value & (1 << 15) ? value - (1 << 16) + 1 : value;
return {local_temperature: parseFloat((temperature / 10).toFixed(1))};
}
case tuya.dataPoints.x5hTempCorrection: {
return {local_temperature_calibration: parseFloat((value / 10).toFixed(1))};
}
case tuya.dataPoints.x5hMode: {
const lookup = {0: 'manual', 1: 'program'};
return {preset: lookup[value]};
}
case tuya.dataPoints.x5hSensorSelection: {
const lookup = {0: 'internal', 1: 'external', 2: 'both'};
return {sensor: lookup[value]};
}
case tuya.dataPoints.x5hOutputReverse: {
return {output_reverse: value};
}
default: {
meta.logger.warn(`fromZigbee:x5h_thermostat: Unrecognized DP #${dp} with data ${JSON.stringify(dpValue)}`);
}
}
},
},
humidity10: {
cluster: 'msRelativeHumidity',
type: ['attributeReport', 'readResponse'],
options: [exposes.options.precision('humidity'), exposes.options.calibration('humidity')],
convert: (model, msg, publish, options, meta) => {
const humidity = parseFloat(msg.data['measuredValue']) / 10.0;
if (humidity >= 0 && humidity <= 100) {
return {humidity: utils.calibrateAndPrecisionRoundOptions(humidity, options, 'humidity')};
}
},
},
temperature_unit: {
cluster: 'manuSpecificTuya_2',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const result = {};
if (msg.data.hasOwnProperty('57355')) {
result.temperature_unit = {'0': 'celsius', '1': 'fahrenheit'}[msg.data['57355']];
}
return result;
},
},
TS011F_electrical_measurement: {
...fz.electrical_measurement,
convert: (model, msg, publish, options, meta) => {
const result = fz.electrical_measurement.convert(model, msg, publish, options, meta);
const lookup = {power: 'activePower', current: 'rmsCurrent', voltage: 'rmsVoltage'};
// Wait 5 seconds before reporting a 0 value as this could be an invalid measurement.
// https://github.com/Koenkk/zigbee2mqtt/issues/16709#issuecomment-1509599046
if (result && ['_TZ3000_gvn91tmx', '_TZ3000_amdymr7l', '_TZ3000_typdpbpg', '_TZ3000_hdopuwv6'].includes(meta.device.manufacturerName)) {
for (const key of ['power', 'current', 'voltage']) {
if (key in result) {
const value = result[key];
clearTimeout(globalStore.getValue(msg.endpoint, key));
if (value === 0) {
const configuredReporting = msg.endpoint.configuredReportings.find((c) =>
c.cluster.name === 'haElectricalMeasurement' && c.attribute.name === lookup[key]);
const time = ((configuredReporting ? configuredReporting.minimumReportInterval : 5) * 2) + 1;
globalStore.putValue(msg.endpoint, key, setTimeout(() => publish({[key]: value}), time * 1000));
delete result[key];
}
}
}
}
return result;
},
},
TS011F_threshold: {
cluster: 'manuSpecificTuya_3',
type: 'raw',
convert: (model, msg, publish, options, meta) => {
const splitToAttributes = (value) => {
const result = {};
const len = value.length;
let i = 0;
while (i < len) {
const key = value.readUInt8(i);
result[key] = [value.readUInt8(i+1), value.readUInt16BE(i+2)];
i += 4;
}
return result;
};
const lookup = {0: 'OFF', 1: 'ON'};
const command = msg.data[2];
const data = msg.data.slice(3);
if (command == 0xE6) {
const value = splitToAttributes(data);
return {
'temperature_threshold': value[0x05][1],
'temperature_breaker': lookup[value[0x05][0]],
'power_threshold': value[0x07][1],
'power_breaker': lookup[value[0x07][0]],
};
}
if (command == 0xE7) {
const value = splitToAttributes(data);
return {
'over_current_threshold': value[0x01][1],
'over_current_breaker': lookup[value[0x01][0]],
'over_voltage_threshold': value[0x03][1],
'over_voltage_breaker': lookup[value[0x03][0]],
'under_voltage_threshold': value[0x04][1],
'under_voltage_breaker': lookup[value[0x04][0]],
};
}
},
},
};
module.exports = [
{
zigbeeModel: ['TS0204'],
model: 'TS0204',
vendor: 'TuYa',
description: 'Gas sensor',
whiteLabel: [{vendor: 'Tesla Smart', model: 'TSL-SEN-GAS'}],
fromZigbee: [fz.ias_gas_alarm_1, fz.ignore_basic_report],
toZigbee: [],
exposes: [e.gas(), e.tamper()],
},
{
zigbeeModel: ['TS0205'],
model: 'TS0205',
vendor: 'TuYa',
description: 'Smoke sensor',
whiteLabel: [{vendor: 'Tesla Smart', model: 'TSL-SEN-SMOKE'}],
fromZigbee: [fz.ias_smoke_alarm_1, fz.battery, fz.ignore_basic_report],
toZigbee: [],
exposes: [e.smoke(), e.battery_low(), e.tamper(), e.battery()],
},
{
zigbeeModel: ['TS0111'],
model: 'TS0111',
vendor: 'TuYa',
description: 'Socket',
extend: tuya.extend.switch(),
},