-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathtuya.ts
10856 lines (10804 loc) · 523 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 fz from '../converters/fromZigbee';
import tz from '../converters/toZigbee';
import * as libColor from '../lib/color';
import {ColorMode, colorModeLookup} from '../lib/constants';
import * as exposes from '../lib/exposes';
import * as legacy from '../lib/legacy';
import {logger} from '../lib/logger';
import {
onOff,
quirkCheckinInterval,
battery,
deviceEndpoints,
light,
iasZoneAlarm,
temperature,
humidity,
identify,
actionEnumLookup,
commandsOnOff,
commandsLevelCtrl,
electricityMeter,
windowCovering,
} from '../lib/modernExtend';
import * as ota from '../lib/ota';
import * as reporting from '../lib/reporting';
import * as globalStore from '../lib/store';
import * as tuya from '../lib/tuya';
import {KeyValue, Definition, Zh, Tz, Fz, Expose, KeyValueAny, KeyValueString, ModernExtend} from '../lib/types';
import * as utils from '../lib/utils';
import {addActionGroup, hasAlreadyProcessedMessage, postfixWithEndpointName} from '../lib/utils';
import * as zosung from '../lib/zosung';
const NS = 'zhc:tuya';
const {tuyaLight} = tuya.modernExtend;
const e = exposes.presets;
const ea = exposes.access;
const fzZosung = zosung.fzZosung;
const tzZosung = zosung.tzZosung;
const ez = zosung.presetsZosung;
const storeLocal = {
getPrivatePJ1203A: (device: Zh.Device) => {
let priv = globalStore.getValue(device, 'private_state');
if (priv === undefined) {
//
// The PJ-1203A is sending quick sequences of messages containing a single datapoint.
// A sequence occurs every `update_frequency` seconds (10s by default)
//
// A typical sequence is composed of two identical groups for channel a and b.
//
// 102 energy_flow_a
// 112 voltage
// 113 current_a
// 101 power_a
// 110 power_factor_a
// 111 ac_frequency
// 115 power_ab
// ---
// 104 energy_flow_b
// 112 voltage
// 114 current_b
// 105 power_b
// 121 power_factor_b
// 111 ac_frequency
// 115 power_ab
//
// It should be noted that when no current is detected on channel x then
// energy_flow_x is not emited and current_x==0, power_x==0 and power_factor_x==100.
//
// The other datapoints are emitted every few minutes.
//
// There is a known issue on the _TZE204_81yrt3lo (with appVersion 74, stackVersion 0 and hwVersion 1).
// The energy_flow datapoints are (incorrectly) emited during the next update. This is quite problematic
// because that means that the direction can be inverted for up to update_frequency seconds.
//
// The features implemented here are
// - cache the datapoints for each channel and publish them together.
// - (OPTIONAL) solve the issue described above by waiting for the next energy flow datapoint
// before publishing the cached channel data.
// - (OPTIONAL) provide signed power instead of energy flow.
// - detect missing or reordered Zigbee message using the Tuya 'seq' attibute and invalidate
// cached data accordingly.
//
priv = {
// Cached values for both channels
sign_a: null,
sign_b: null,
power_a: null,
power_b: null,
current_a: null,
current_b: null,
power_factor_a: null,
power_factor_b: null,
timestamp_a: null,
timestamp_b: null,
// Used to detect missing or misordered messages.
last_seq: -99999,
// Do all PJ-1203A increment seq by 256? If not, then this is
// the value that will have to be customized.
seq_inc: 256,
// Also need to save the last published SIGNED values of
// power_a and power_b to recompute power_ab on the fly.
pub_power_a: null,
pub_power_b: null,
recompute_power_ab: function (result: KeyValueAny) {
let modified = false;
if ('power_a' in result) {
this.pub_power_a = result.power_a * (result.energy_flow_a == 'producing' ? -1 : 1);
modified = true;
}
if ('power_b' in result) {
this.pub_power_b = result.power_b * (result.energy_flow_b == 'producing' ? -1 : 1);
modified = true;
}
if (modified) {
if (this.pub_power_a !== null && this.pub_power_b !== null) {
// Cancel and reapply the scaling by 10 to avoid floating-point rounding errors
// such as 79.8 - 37.1 = 42.699999999999996
result['power_ab'] = Math.round(10 * this.pub_power_a + 10 * this.pub_power_b) / 10;
}
}
},
flush: function (result: KeyValueAny, channel: string, options: KeyValue) {
const sign = this['sign_' + channel];
const power = this['power_' + channel];
const current = this['current_' + channel];
const powerFactor = this['power_factor_' + channel];
this['sign_' + channel] = this['power_' + channel] = this['current_' + channel] = this['power_factor_' + channel] = null;
// Only publish if the set is complete otherwise discard everything.
if (sign !== null && power !== null && current !== null && powerFactor !== null) {
const signedPowerKey = 'signed_power_' + channel;
const signedPower = options.hasOwnProperty(signedPowerKey) ? options[signedPowerKey] : false;
if (signedPower) {
result['power_' + channel] = sign * power;
result['energy_flow_' + channel] = 'sign';
} else {
result['power_' + channel] = power;
result['energy_flow_' + channel] = sign > 0 ? 'consuming' : 'producing';
}
result['timestamp_' + channel] = this['timestamp_' + channel];
result['current_' + channel] = current;
result['power_factor_' + channel] = powerFactor;
this.recompute_power_ab(result);
return true;
}
return false;
},
// When the device does not detect any flow, it stops sending
// the energy_flow datapoint (102 and 104) and always set
// current_x=0, power_x=0 and power_factor_x=100.
//
// So if we see a datapoint with current==0 or power==0
// then we can safely assume that we are in that zero energy state.
//
// Also, the publication of a zero energy state is not delayed
// when option late_energy_flow_a|b is set.
flushZero: function (result: KeyValueAny, channel: string, options: KeyValue) {
this['sign_' + channel] = +1;
this['power_' + channel] = 0;
this['timestamp_' + channel] = new Date().toISOString();
this['current_' + channel] = 0;
this['power_factor_' + channel] = 100;
this.flush(result, channel, options);
},
clear: function () {
priv.sign_a = null;
priv.sign_b = null;
priv.power_a = null;
priv.power_b = null;
priv.current_a = null;
priv.current_b = null;
priv.power_factor_a = null;
priv.power_factor_b = null;
},
};
globalStore.putValue(device, 'private_state', priv);
}
return priv;
},
};
const convLocal = {
energyFlowPJ1203A: (channel: string) => {
return {
from: (v: number, meta: Fz.Meta, options: KeyValue) => {
const priv = storeLocal.getPrivatePJ1203A(meta.device);
const result = {};
priv['sign_' + channel] = v == 1 ? -1 : +1;
const lateEnergyFlowKey = 'late_energy_flow_' + channel;
const lateEnergyFlow = options.hasOwnProperty(lateEnergyFlowKey) ? options[lateEnergyFlowKey] : false;
if (lateEnergyFlow) {
priv.flush(result, channel, options);
}
return result;
},
};
},
powerPJ1203A: (channel: string) => {
return {
from: (v: number, meta: Fz.Meta, options: KeyValue) => {
const priv = storeLocal.getPrivatePJ1203A(meta.device);
const result = {};
priv['power_' + channel] = v / 10;
priv['timestamp_' + channel] = new Date().toISOString();
if (v == 0) {
priv.flushZero(result, channel, options);
return result;
}
return result;
},
};
},
currentPJ1203A: (channel: string) => {
return {
from: (v: number, meta: Fz.Meta, options: KeyValue) => {
const priv = storeLocal.getPrivatePJ1203A(meta.device);
const result = {};
priv['current_' + channel] = v / 1000;
if (v == 0) {
priv.flushZero(result, channel, options);
return result;
}
return result;
},
};
},
powerFactorPJ1203A: (channel: string) => {
return {
from: (v: number, meta: Fz.Meta, options: KeyValue) => {
const priv = storeLocal.getPrivatePJ1203A(meta.device);
const result = {};
priv['power_factor_' + channel] = v;
const lateEnergyFlowKey = 'late_energy_flow_' + channel;
const lateEnergyFlow = options.hasOwnProperty(lateEnergyFlowKey) ? options[lateEnergyFlowKey] : false;
if (!lateEnergyFlow) {
priv.flush(result, channel, options);
}
return result;
},
};
},
powerAbPJ1203A: () => {
return {
// power_ab datapoint is broken and will be recomputed so ignore it.
from: (v: number, meta: Fz.Meta, options: KeyValue) => {
return {};
},
};
},
};
const tzLocal = {
TS030F_border: {
key: ['border'],
convertSet: async (entity, key, value, meta) => {
const lookup = {up: 0, down: 1, up_delete: 2, down_delete: 3};
await entity.write(0xe001, {0xe001: {value: utils.getFromLookup(value, lookup), type: 0x30}});
},
} satisfies Tz.Converter,
TS0726_switch_mode: {
key: ['switch_mode'],
convertSet: async (entity, key, value, meta) => {
await entity.write(0xe001, {0xd020: {value: utils.getFromLookup(value, {switch: 0, scene: 1}), type: 0x30}});
return {state: {switch_mode: value}};
},
} satisfies Tz.Converter,
led_control: {
key: ['brightness', 'color', 'color_temp', 'transition'],
options: [exposes.options.color_sync()],
convertSet: async (entity, _key, _value, meta) => {
const newState: KeyValue = {};
// 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});
}
// 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 = typeof meta.message.transition === 'number' ? meta.message.transition * 10 : 0.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
// @ts-expect-error
hue: (meta.state.color ?? {}).hue ?? 0, // red
// @ts-expect-error
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 brightness = utils.toNumber(newSettings.brightness, 'brightness');
const zclData = {
brightness: utils.mapNumberRange(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));
return {state: newState};
},
convertGet: async (entity, key, meta) => {
await entity.read('lightingColorCtrl', ['currentHue', 'currentSaturation', 'currentLevel', 'tuyaRgbMode', 'colorTemperature']);
},
} satisfies Tz.Converter,
TS0504B_color: {
key: ['color'],
convertSet: async (entity, key, value, meta) => {
const color = libColor.Color.fromConverterArg(value);
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: KeyValue = {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) as KeyValue};
} else {
return await tz.light_color.convertSet(entity, key, value, meta);
}
},
convertGet: tz.light_color.convertGet,
} satisfies Tz.Converter,
TS0224: {
key: ['light', 'duration', 'volume'],
convertSet: async (entity, key, value, meta) => {
if (key === 'light') {
utils.assertString(value, '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: KeyValue = {mute: 0, low: 10, medium: 30, high: 50};
utils.assertString(value, 'volume');
const lookupValue = lookup[value];
value = value.toLowerCase();
utils.validateValue(value, Object.keys(lookup));
await entity.write('ssIasWd', {0x0002: {value: lookupValue, type: 0x0a}}, utils.getOptions(meta.mapped, entity));
}
return {state: {[key]: value}};
},
} satisfies Tz.Converter,
temperature_unit: {
key: ['temperature_unit'],
convertSet: async (entity, key, value, meta) => {
switch (key) {
case 'temperature_unit': {
utils.assertString(value, 'temperature_unit');
await entity.write('manuSpecificTuya_2', {'57355': {value: {celsius: 0, fahrenheit: 1}[value], type: 48}});
break;
}
default: // Unknown key
logger.warning(`Unhandled key ${key}`, NS);
}
},
} satisfies Tz.Converter,
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) => {
const onOffLookup = {on: 1, off: 0};
switch (key) {
case 'temperature_threshold': {
const state = meta.state['temperature_breaker'];
const buf = Buffer.from([5, utils.getFromLookup(state, onOffLookup), 0, utils.toNumber(value, 'temperature_threshold')]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'temperature_breaker': {
const threshold = meta.state['temperature_threshold'];
const number = utils.toNumber(threshold, 'temperature_threshold');
const buf = Buffer.from([5, utils.getFromLookup(value, onOffLookup), 0, number]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'power_threshold': {
const state = meta.state['power_breaker'];
const buf = Buffer.from([7, utils.getFromLookup(state, onOffLookup), 0, utils.toNumber(value, 'power_breaker')]);
await entity.command('manuSpecificTuya_3', 'setOptions2', {data: buf});
break;
}
case 'power_breaker': {
const threshold = meta.state['power_threshold'];
const number = utils.toNumber(threshold, 'power_breaker');
const buf = Buffer.from([7, utils.getFromLookup(value, onOffLookup), 0, number]);
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, utils.getFromLookup(state, onOffLookup), 0, utils.toNumber(value, 'over_current_threshold')]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'over_current_breaker': {
const threshold = meta.state['over_current_threshold'];
const number = utils.toNumber(threshold, 'over_current_threshold');
const buf = Buffer.from([1, utils.getFromLookup(value, onOffLookup), 0, number]);
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, utils.getFromLookup(state, onOffLookup), 0, utils.toNumber(value, 'over_voltage_breaker')]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'over_voltage_breaker': {
const threshold = meta.state['over_voltage_threshold'];
const number = utils.toNumber(threshold, 'over_voltage_threshold');
const buf = Buffer.from([3, utils.getFromLookup(value, onOffLookup), 0, number]);
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, utils.getFromLookup(state, onOffLookup), 0, utils.toNumber(value, 'under_voltage_threshold')]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
case 'under_voltage_breaker': {
const threshold = meta.state['under_voltage_threshold'];
const number = utils.toNumber(threshold, 'under_voltage_breaker');
const buf = Buffer.from([4, utils.getFromLookup(value, onOffLookup), 0, number]);
await entity.command('manuSpecificTuya_3', 'setOptions3', {data: buf});
break;
}
default: // Unknown key
logger.warning(`Unhandled key ${key}`, NS);
}
},
} satisfies Tz.Converter,
};
const fzLocal = {
TS0726_action: {
cluster: 'genOnOff',
type: ['commandTuyaAction'],
convert: (model, msg, publish, options, meta) => {
return {action: `scene_${msg.endpoint.ID}`};
},
} satisfies Fz.Converter,
TS0222_humidity: {
...fz.humidity,
convert: async (model, msg, publish, options, meta) => {
const result = await fz.humidity.convert(model, msg, publish, options, meta);
if (result) result.humidity *= 10;
return result;
},
} satisfies Fz.Converter,
scene_recall: {
cluster: 'genScenes',
type: 'commandRecall',
convert: (model, msg, publish, options, meta) => {
if (hasAlreadyProcessedMessage(msg, model)) return;
const payload = {action: postfixWithEndpointName(`scene_${msg.data.sceneid}`, msg, model, meta)};
addActionGroup(payload, msg, model);
return payload;
},
} satisfies Fz.Converter,
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}`};
},
} satisfies Fz.Converter,
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);
},
} satisfies Fz.Converter,
TS0201_humidity: {
...fz.humidity,
convert: (model, msg, publish, options, meta) => {
if (['_TZ3210_ncw88jfq', '_TZ3000_ywagc4rj'].includes(meta.device.manufacturerName)) {
msg.data['measuredValue'] *= 10;
}
return fz.humidity.convert(model, msg, publish, options, meta);
},
} satisfies Fz.Converter,
humidity10: {
cluster: 'msRelativeHumidity',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const humidity = parseFloat(msg.data['measuredValue']) / 10.0;
if (humidity >= 0 && humidity <= 100) {
return {humidity};
}
},
} satisfies Fz.Converter,
temperature_unit: {
cluster: 'manuSpecificTuya_2',
type: ['attributeReport', 'readResponse'],
convert: (model, msg, publish, options, meta) => {
const result: KeyValue = {};
if (msg.data.hasOwnProperty('57355')) {
result.temperature_unit = utils.getFromLookup(msg.data['57355'], {'0': 'celsius', '1': 'fahrenheit'});
}
return result;
},
} satisfies Fz.Converter,
TS011F_electrical_measurement: {
...fz.electrical_measurement,
convert: async (model, msg, publish, options, meta) => {
const result = (await fz.electrical_measurement.convert(model, msg, publish, options, meta)) ?? {};
const lookup: KeyValueString = {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) {
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(() => {
const payload = {[key]: value};
// Device takes a lot of time to report power 0 in some cases. When current == 0 we can assume power == 0
// https://github.com/Koenkk/zigbee2mqtt/discussions/19680#discussioncomment-7868445
if (key === 'current') {
payload.power = 0;
}
publish(payload);
}, time * 1000),
);
delete result[key];
}
}
}
}
// Device takes a lot of time to report power 0 in some cases. When the state is OFF we can assume power == 0
// https://github.com/Koenkk/zigbee2mqtt/discussions/19680#discussioncomment-7868445
if (meta.state.state === 'OFF') {
result.power = 0;
}
return result;
},
} satisfies Fz.Converter,
TS011F_threshold: {
cluster: 'manuSpecificTuya_3',
type: 'raw',
convert: (model, msg, publish, options, meta) => {
const splitToAttributes = (value: Buffer): KeyValueAny => {
const result: KeyValue = {};
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: KeyValue = {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]],
};
}
},
} satisfies Fz.Converter,
PJ1203A_sync_time_increase_seq: {
cluster: 'manuSpecificTuya',
type: ['commandMcuSyncTime'],
convert: (model, msg, publish, options, meta) => {
const priv = storeLocal.getPrivatePJ1203A(meta.device);
priv.last_seq += priv.seq_inc;
},
} satisfies Fz.Converter,
PJ1203A_strict_fz_datapoints: {
...tuya.fz.datapoints,
convert: (model, msg, publish, options, meta) => {
// Uncomment the next line to test the behavior when random messages are lost
// if ( Math.random() < 0.05 ) return;
const priv = storeLocal.getPrivatePJ1203A(meta.device);
// Detect missing or re-ordered messages but allow duplicate messages (should we?).
const expectedSeq = (priv.last_seq + priv.seq_inc) & 0xffff;
if (msg.data.seq != expectedSeq && msg.data.seq != priv.last_seq) {
logger.debug(`[PJ1203A] Missing or re-ordered message detected: Got seq=${msg.data.seq}, expected ${priv.next_seq}`, NS);
priv.clear();
}
priv.last_seq = msg.data.seq;
// And finally, process the datapoint using tuya.fz.datapoints
return tuya.fz.datapoints.convert(model, msg, publish, options, meta);
},
} satisfies Fz.Converter,
};
const modernExtendLocal = {
dpTHZBSettings(): ModernExtend {
const exp = e
.composite('auto_settings', 'auto_settings', ea.STATE_SET)
.withFeature(e.enum('enabled', ea.STATE_SET, ['on', 'off', 'none']).withDescription('Enable auto settings'))
.withFeature(e.enum('temp_greater_then', ea.STATE_SET, ['on', 'off', 'none']).withDescription('Greater action'))
.withFeature(
e
.numeric('temp_greater_value', ea.STATE_SET)
.withValueMin(-20)
.withValueMax(80)
.withValueStep(0.1)
.withUnit('*C')
.withDescription('Temperature greater than value'),
)
.withFeature(e.enum('temp_lower_then', ea.STATE_SET, ['on', 'off', 'none']).withDescription('Lower action'))
.withFeature(
e
.numeric('temp_lower_value', ea.STATE_SET)
.withValueMin(-20)
.withValueMax(80)
.withValueStep(0.1)
.withUnit('*C')
.withDescription('Temperature lower than value'),
);
const handlers: [Fz.Converter[], Tz.Converter[]] = tuya.getHandlersForDP('auto_settings', 0x77, tuya.dataTypes.string, {
from: (value: string) => {
let result = {
enabled: 'none',
temp_greater_then: 'none',
temp_greater_value: 0,
temp_lower_then: 'none',
temp_lower_value: 0,
};
const buf = Buffer.from(value, 'hex');
if (buf.length > 0) {
const enabled = buf[0];
const gr = buf[1];
const grValue = buf.readInt32LE(2) / 10;
const grAction = buf[6];
const lo = buf[7];
const loValue = buf.readInt32LE(8) / 10;
const loAction = buf[13];
result = {
enabled: {0x00: 'on', 0x80: 'off'}[enabled],
temp_greater_then: gr !== 0xff ? {0x01: 'on', 0x00: 'off'}[grAction] : 'none',
temp_greater_value: grValue,
temp_lower_then: lo !== 0xff ? {0x01: 'on', 0x00: 'off'}[loAction] : 'none',
temp_lower_value: loValue,
};
}
return result;
},
to: (value: KeyValueAny) => {
let result = '';
if (value.enabled !== 'none') {
const enabled = utils.getFromLookup(value.enabled, {on: 0x00, off: 0x80});
const gr = value.temp_greater_then == 'none' ? 0xff : 0x00;
const grAction = utils.getFromLookup(value.temp_greater_then, {on: 0x01, off: 0x00, none: 0x00});
const lo = value.temp_lower_then == 'none' ? 0xff : 0x00;
const loAction = utils.getFromLookup(value.temp_lower_then, {on: 0x01, off: 0x00, none: 0x00});
const buf = Buffer.alloc(13);
buf.writeUInt8(enabled, 0);
buf.writeUInt8(gr, 1);
buf.writeInt32LE(value.temp_greater_value * 10, 2);
buf.writeUInt8(grAction, 6);
buf.writeUInt8(lo, 7);
buf.writeInt32LE(value.temp_lower_value * 10, 8);
buf.writeUInt8(loAction, 12);
result = buf.toString('hex');
}
return result;
},
});
return {exposes: [exp], fromZigbee: handlers[0], toZigbee: handlers[1], isModernExtend: true};
},
};
const definitions: Definition[] = [
{
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'},
{vendor: 'Dongguan Daying Electornics Technology', model: 'YG400A'},
tuya.whitelabel('Tuya', 'TS0205_smoke_2', 'Smoke sensor', ['_TZ3210_up3pngle']),
],
fromZigbee: [fz.ias_smoke_alarm_1, fz.ignore_basic_report],
toZigbee: [],
exposes: [e.smoke(), e.battery_low(), e.tamper()],
extend: [battery()],
},
{
zigbeeModel: ['TS0111'],
model: 'TS0111',
vendor: 'Tuya',
description: 'Socket',
extend: [tuya.modernExtend.tuyaOnOff()],
},
{
zigbeeModel: ['TS0218'],
model: 'TS0218',
vendor: 'Tuya',
description: 'Button',
fromZigbee: [legacy.fromZigbee.TS0218_click, fz.battery],
exposes: [e.battery(), e.action(['click'])],
toZigbee: [],
},
{
zigbeeModel: ['TS0203'],
model: 'TS0203',
vendor: 'Tuya',
description: 'Door sensor',
fromZigbee: [fz.ias_contact_alarm_1, fz.battery, fz.ignore_basic_report, fz.ias_contact_alarm_1_report],
toZigbee: [],
whiteLabel: [
{vendor: 'CR Smart Home', model: 'TS0203'},
{vendor: 'Tuya', model: 'iH-F001'},
{vendor: 'Tesla Smart', model: 'TSL-SEN-DOOR'},
{vendor: 'Cleverio', model: 'SS100'},
tuya.whitelabel('Niceboy', 'ORBIS Windows & Door Sensor', 'Door sensor', ['_TZ3000_qrldbmfn']),
tuya.whitelabel('Tuya', 'ZD06', 'Door window sensor', ['_TZ3000_rcuyhwe3']),
tuya.whitelabel('Tuya', 'ZD08', 'Door sensor', ['_TZ3000_7d8yme6f']),
tuya.whitelabel('Tuya', 'MC500A', 'Door sensor', ['_TZ3000_2mbfxlzr']),
tuya.whitelabel('Tuya', '19DZT', 'Door sensor', ['_TZ3000_n2egfsli']),
tuya.whitelabel('Tuya', 'DS04', 'Door sensor', ['_TZ3000_yfekcy3n']),
tuya.whitelabel('Moes', 'ZSS-JM-GWM-C-MS', 'Smart door and window sensor', ['_TZ3000_decxrtwa']),
tuya.whitelabel('Moes', 'ZSS-X-GWM-C', 'Door/window magnetic sensor', ['_TZ3000_gntwytxo']),
tuya.whitelabel('Luminea', 'ZX-5232', 'Smart door and window sensor', ['_TZ3000_4ugnzsli']),
tuya.whitelabel('QA', 'QASD1', 'Door sensor', ['_TZ3000_udyjylt7']),
tuya.whitelabel('Nous', 'E3', 'Door sensor', ['_TZ3000_v7chgqso']),
],
exposes: (device, options) => {
const exps: Expose[] = [e.contact(), e.battery(), e.battery_voltage()];
const noTamperModels = [
// manufacturerName for models without a tamper sensor
'_TZ3000_rcuyhwe3', // Tuya ZD06
'_TZ3000_2mbfxlzr', // Tuya MC500A
'_TZ3000_n2egfsli', // Tuya 19DZT
'_TZ3000_yfekcy3n', // Tuya DS04
'_TZ3000_bpkijo14',
'_TZ3000_gntwytxo', // Moes ZSS-X-GWM-C
'_TZ3000_4ugnzsli', // Luminea ZX-5232
];
if (!device || !noTamperModels.includes(device.manufacturerName)) {
exps.push(e.tamper());
}
const noBatteryLowModels = ['_TZ3000_26fmupbb', '_TZ3000_oxslv1c9', '_TZ3000_osu834un'];
if (!device || !noBatteryLowModels.includes(device.manufacturerName)) {
exps.push(e.battery_low());
}
exps.push(e.linkquality());
return exps;
},
meta: {
battery: {
// These sensors do send a Battery Percentage Remaining (0x0021)
// value, but is usually incorrect. For example, a coin battery tested
// with a load tester may show 80%, but report 2.5V / 1%. This voltage
// calculation matches what ZHA does by default.
// https://github.com/Koenkk/zigbee2mqtt/discussions/17337
// https://github.com/zigpy/zha-device-handlers/blob/c6ed94a52a469e72b32ece2a92d528060c7fd034/zhaquirks/__init__.py#L195-L228
voltageToPercentage: '3V_1500_2800',
},
},
configure: async (device, coordinatorEndpoint) => {
try {
const endpoint = device.getEndpoint(1);
await reporting.bind(endpoint, coordinatorEndpoint, ['genPowerCfg']);
await reporting.batteryPercentageRemaining(endpoint);
await reporting.batteryVoltage(endpoint);
} catch (error) {
/* Fails for some*/
}
},
},
{
fingerprint: tuya.fingerprint('TS0203', ['_TZ3210_jowhpxop']),
model: 'TS0203_1',
vendor: 'Tuya',
description: 'Door sensor with scene switch',
fromZigbee: [tuya.fz.datapoints, fz.ias_contact_alarm_1, fz.battery, fz.ignore_basic_report, fz.ias_contact_alarm_1_report],
toZigbee: [tuya.tz.datapoints],
onEvent: tuya.onEventSetTime,
configure: tuya.configureMagicPacket,
exposes: [e.action(['single', 'double', 'hold']), e.contact(), e.battery_low(), e.tamper(), e.battery(), e.battery_voltage()],
meta: {
tuyaDatapoints: [[101, 'action', tuya.valueConverterBasic.lookup({single: 0, double: 1, hold: 2})]],
},
whiteLabel: [tuya.whitelabel('Linkoze', 'LKDSZ001', 'Door sensor with scene switch', ['_TZ3210_jowhpxop'])],
},
{
fingerprint: [{modelID: 'TS0021', manufacturerName: '_TZ3210_3ulg9kpo'}],
model: 'LKWSZ211',
vendor: 'Tuya',
description: 'Scene remote with 2 keys',
fromZigbee: [tuya.fz.datapoints, fz.ignore_basic_report],
toZigbee: [tuya.tz.datapoints],
onEvent: tuya.onEventSetTime,
configure: tuya.configureMagicPacket,
exposes: [
e.battery(),
e.action(['button_1_single', 'button_1_double', 'button_1_hold', 'button_2_single', 'button_2_double', 'button_2_hold']),
],
meta: {
tuyaDatapoints: [
[
1,
'action',
tuya.valueConverterBasic.lookup({
button_1_single: tuya.enum(0),
button_1_double: tuya.enum(1),
button_1_hold: tuya.enum(2),
}),
],
[
2,
'action',
tuya.valueConverterBasic.lookup({
button_2_single: tuya.enum(0),
button_2_double: tuya.enum(1),
button_2_hold: tuya.enum(2),
}),
],
[10, 'battery', tuya.valueConverter.raw],
],
},
whiteLabel: [
tuya.whitelabel('Linkoze', 'LKWSZ211', 'Wireless switch (2-key)', ['_TZ3210_3ulg9kpo']),
tuya.whitelabel('Adaprox', 'LKWSZ211', 'Remote wireless switch (2-key)', ['_TZ3210_3ulg9kpo']),
],
},
{
fingerprint: [
{modelID: 'TS0601', manufacturerName: '_TZE200_bq5c8xfe'},
{modelID: 'TS0601', manufacturerName: '_TZE200_bjawzodf'},
{modelID: 'TS0601', manufacturerName: '_TZE200_qyflbnbj'},
{modelID: 'TS0601', manufacturerName: '_TZE200_vs0skpuc'},
{modelID: 'TS0601', manufacturerName: '_TZE200_44af8vyi'},
{modelID: 'TS0601', manufacturerName: '_TZE200_zl1kmjqx'},
],
model: 'TS0601_temperature_humidity_sensor_1',
vendor: 'Tuya',
description: 'Temperature & humidity sensor',
fromZigbee: [legacy.fromZigbee.tuya_temperature_humidity_sensor],
toZigbee: [],
exposes: (device, options) => {
const exps: Expose[] = [e.temperature(), e.humidity(), e.battery()];
if (!device || device.manufacturerName === '_TZE200_qyflbnbj') {
exps.push(e.battery_low());
exps.push(e.enum('battery_level', ea.STATE, ['low', 'middle', 'high']).withDescription('Battery level state'));
}
exps.push(e.linkquality());
return exps;
},
},
{
fingerprint: [{modelID: 'TS0601', manufacturerName: '_TZE200_mfamvsdb'}],
model: 'F00MB00-04-1',
vendor: 'FORIA',
description: '4 scenes switch',
extend: [
tuya.modernExtend.tuyaMagicPacket(),
tuya.modernExtend.combineActions([
tuya.modernExtend.dpAction({dp: 1, lookup: {scene_1: 0}}),
tuya.modernExtend.dpAction({dp: 2, lookup: {scene_2: 0}}),
tuya.modernExtend.dpAction({dp: 3, lookup: {scene_3: 0}}),
tuya.modernExtend.dpAction({dp: 4, lookup: {scene_4: 0}}),
]),
tuya.modernExtend.dpBinary({
name: 'vibration',