forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device_access_fn.cpp
2091 lines (1689 loc) · 61.5 KB
/
device_access_fn.cpp
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
/*
* Copyright (c) 2021 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QTimeZone>
#include "device_access_fn.h"
#include "device_descriptions.h"
#include "device_js/device_js.h"
#include "ias_zone.h"
#include "resource.h"
#include "zcl/zcl.h"
#define TIME_CLUSTER_ID 0x000A
#define TIME_ATTRID_TIME 0x0000
#define TIME_ATTRID_LOCAL_TIME 0x0007
#define TIME_ATTRID_LAST_SET_TIME 0x0008
/*
Documentation for manufacturer specific Tuya cluster (0xEF00)
https://developer.tuya.com/en/docs/iot-device-dev/tuya-zigbee-universal-docking-access-standard?id=K9ik6zvofpzql
Tuya ZCL insights
https://github.com/TuyaInc/tuya_zigbee_sdk/blob/master/silicon_labs_zigbee/include/zigbee_attr.h
Basic cluster (0x0000)
-------------
0x0001 Application version:: 0b 01 00 0001 = 1.0.1 ie 0x41 for 1.0.1
0x0004 Manufacturer name: XXX…XXX (16 bytes in length, consisting of an 8-byte prefix and an 8-byte PID)
0-7 bytes: _ TZE600_
8-16 bytes: PID (created and provided by the product manager in the platform or self-service)
Tuya cluster (0xEF00)
---------------------
https://developer.tuya.com/en/docs/iot-device-dev/tuya-zigbee-universal-docking-access-standard?id=K9ik6zvofpzql
Zigbee generic docking is suitable for scenarios where the Zigbee standard protocol is not supported or not very suitable.
ZDP Simple Descriptor Device Id (0x0051)
Frame control for outgoing commands:
deCONZ::ZclFCClusterCommand
deCONZ::ZclFCDirectionClientToServer
deCONZ::ZclFCDisableDefaultResponse
DP data format
--------------
DPID U8 Datapoint serial number
Type U8 Datatype in value
Name Id Length
------------------------------
raw 0x00
bool 0x01
value 0x02
string 0x03
enum 0x04
bitmap 0x05
Length U16 Length of Value
Value 1/2/4/N The value as big endian
ZCL Payload of comamnds
-----------------------
Example MoesGo switch TY_DATA_REPORT
00 4c sequence number
02 DPID
02 Type: Value
00 04 Length: 4
00 00 00 15
*/
#define TUYA_CLUSTER_ID 0xEF00
enum TuyaCommandId : unsigned char
{
TY_DATA_REQUEST = 0x00,
TY_DATA_RESPONSE = 0x01,
TY_DATA_REPORT = 0x02,
TY_DATA_QUERY = 0x03,
TUYA_MCU_VERSION_REQ = 0x10,
TUYA_MCU_VERSION_RSP = 0x11,
TUYA_MCU_OTA_NOTIFY = 0x12,
TUYA_MCU_OTA_BLOCK_DATA_REQ = 0x13,
TUYA_MCU_OTA_BLOCK_DATA_RSP = 0x14,
TUYA_MCU_OTA_RESULT = 0x15,
TUYA_MCU_SYNC_TIME = 0x24
};
enum TuyaDataType : unsigned char
{
TuyaDataTypeRaw = 0x00,
TuyaDataTypeBool = 0x01,
TuyaDataTypeValue = 0x02,
TuyaDataTypeString = 0x03,
TuyaDataTypeEnum = 0x04,
TuyaDataTypeBitmap = 0x05
};
enum DA_Constants
{
BroadcastEndpoint = 255, //! Accept incoming commands from any endpoint.
AutoEndpoint = 0 //! Use src/dst endpoint of the related Resource (uniqueid).
};
struct ParseFunction
{
ParseFunction(const QString &_name, const int _arity, ParseFunction_t _fn) :
name(_name),
arity(_arity),
fn(_fn)
{ }
QString name;
int arity = 0; // number of parameters given by the device description file
ParseFunction_t fn = nullptr;
};
struct ReadFunction
{
ReadFunction(const QString &_name, const int _arity, ReadFunction_t _fn) :
name(_name),
arity(_arity),
fn(_fn)
{ }
QString name;
int arity = 0; // number of parameters given by the device description file
ReadFunction_t fn = nullptr;
};
struct WriteFunction
{
WriteFunction(const QString &_name, const int _arity, WriteFunction_t _fn) :
name(_name),
arity(_arity),
fn(_fn)
{ }
QString name;
int arity = 0; // number of parameters given by the device description file
WriteFunction_t fn = nullptr;
};
quint8 zclNextSequenceNumber(); // todo defined in de_web_plugin_private.h
/*! Helper to get an unsigned int from \p var which might be a number or string value.
\param var - Holds the string or number.
\param max – Upper bound of the allowed value.
\param ok – true if var holds and uint which is <= \p max.
*/
uint variantToUint(const QVariant &var, size_t max, bool *ok)
{
Q_ASSERT(ok);
*ok = false;
if (var.isNull())
{
return 0;
}
const auto val = var.toString().toUInt(ok, 0);
*ok = *ok && val <= max;
return *ok ? val : 0;
}
/*! Extracts common ZCL parameters from an object.
*/
static ZCL_Param getZclParam(const QVariantMap ¶m)
{
ZCL_Param result{};
if (!param.contains(QLatin1String("cl")))
{
return result;
}
bool ok = true;
result.endpoint = param.contains("ep") ? variantToUint(param["ep"], UINT8_MAX, &ok) : quint8(AutoEndpoint);
result.clusterId = ok ? variantToUint(param["cl"], UINT16_MAX, &ok) : 0;
result.manufacturerCode = ok && param.contains("mf") ? variantToUint(param["mf"], UINT16_MAX, &ok) : 0;
if (param.contains(QLatin1String("cmd"))) // optional
{
result.commandId = variantToUint(param["cmd"], UINT8_MAX, &ok);
result.hasCommandId = ok ? 1 : 0;
}
else
{
result.hasCommandId = 0;
}
const auto ignoreSeqno = QLatin1String("noseq");
if (param.contains(ignoreSeqno))
{
result.ignoreResponseSeq = param.value(ignoreSeqno).toBool() ? 1 : 0;
}
else
{
result.ignoreResponseSeq = 0;
}
result.attributeCount = 0;
const auto attr = param[QLatin1String("at")]; // optional
if (!ok)
{ }
else if (attr.type() == QVariant::String)
{
result.attributes[result.attributeCount] = variantToUint(attr, UINT16_MAX, &ok);
result.attributeCount = 1;
}
else if (attr.type() == QVariant::List)
{
const auto arr = attr.toList();
for (const auto &at : arr)
{
if (result.attributeCount == ZCL_Param::MaxAttributes)
{
break;
}
if (ok && at.type() == QVariant::String)
{
result.attributes[result.attributeCount] = variantToUint(at, UINT16_MAX, &ok);
result.attributeCount++;
}
}
ok = result.attributeCount == size_t(arr.size());
}
else if (param["eval"].toString().contains("Attr")) // guard against missing "at"
{
ok = false;
}
result.valid = ok;
return result;
}
quint8 resolveAutoEndpoint(const Resource *r)
{
quint8 result = AutoEndpoint;
// hack to get endpoint. todo find better solution
const auto ls = r->item(RAttrUniqueId)->toString().split('-', SKIP_EMPTY_PARTS);
if (ls.size() >= 2)
{
bool ok = false;
uint ep = ls[1].toUInt(&ok, 16);
if (ok && ep < BroadcastEndpoint)
{
result = ep;
}
}
return result;
}
/*! Evaluates an items Javascript expression for a received attribute.
*/
bool evalZclAttribute(Resource *r, ResourceItem *item, const deCONZ::ApsDataIndication &ind, const deCONZ::ZclFrame &zclFrame, const deCONZ::ZclAttribute &attr, const QVariant &parseParameters)
{
bool ok = false;
const auto &zclParam = item->zclParam();
for (size_t i = 0; i < zclParam.attributeCount; i++)
{
if (zclParam.attributes[i] == attr.id())
{
ok = true;
break;
}
}
if (!ok)
{
return false;
}
const auto expr = parseParameters.toMap()["eval"].toString();
if (!expr.isEmpty())
{
DeviceJs &engine = *DeviceJs::instance();
engine.reset();
engine.setResource(r);
engine.setItem(item);
engine.setZclAttribute(attr);
engine.setZclFrame(zclFrame);
engine.setApsIndication(ind);
if (engine.evaluate(expr) == JsEvalResult::Ok)
{
const auto res = engine.result();
if (res.isValid())
{
DBG_Printf(DBG_DDF, "%s/%s expression: %s --> %s\n", r->item(RAttrUniqueId)->toCString(), item->descriptor().suffix, qPrintable(expr), qPrintable(res.toString()));
// item->setValue(res, ResourceItem::SourceDevice);
return true;
}
}
else
{
DBG_Printf(DBG_DDF, "failed to evaluate expression for %s/%s: %s, err: %s\n", r->item(RAttrUniqueId)->toCString(), item->descriptor().suffix, qPrintable(expr), qPrintable(engine.errorString()));
}
}
return false;
}
/*! Evaluates an items Javascript expression for a received ZCL frame.
*/
bool evalZclFrame(Resource *r, ResourceItem *item, const deCONZ::ApsDataIndication &ind, const deCONZ::ZclFrame &zclFrame, const QVariant &parseParameters)
{
const auto expr = parseParameters.toMap()["eval"].toString();
if (!expr.isEmpty())
{
DeviceJs &engine = *DeviceJs::instance();
engine.reset();
engine.setResource(r);
engine.setItem(item);
engine.setZclFrame(zclFrame);
engine.setApsIndication(ind);
if (engine.evaluate(expr) == JsEvalResult::Ok)
{
const auto res = engine.result();
if (res.isValid())
{
if (DBG_IsEnabled(DBG_DDF))
{
DBG_Printf(DBG_DDF, "expression: %s --> %s\n", qPrintable(expr), qPrintable(res.toString()));
}
return true;
}
}
else
{
DBG_Printf(DBG_DDF, "failed to evaluate expression for %s/%s: %s, err: %s\n", qPrintable(r->item(RAttrUniqueId)->toString()), item->descriptor().suffix, qPrintable(expr), qPrintable(engine.errorString()));
}
}
return false;
}
/*! A general purpose function to map number values of a source item to a string which is stored in \p item .
The item->parseParameters() is expected to be an object (given in the device description file).
{"fn": "numtostr", "srcitem": suffix, "op": operator, "to": array}
- srcitem: the suffix of the source item which holds the numeric value
- op: (lt | le | eq | gt | ge) the operator used to match the 'to' array
- to: [number, string, [number, string], ...] an sorted array to map 'number -> string' with the given operator
Example: { "parse": {"fn": "numtostr", "srcitem": "state/airqualityppb", "op": "le", "to": [65, "good", 65535, "bad"] }
*/
bool parseNumericToString(Resource *r, ResourceItem *item, const deCONZ::ApsDataIndication &ind, const deCONZ::ZclFrame &zclFrame, const QVariant &parseParameters)
{
Q_UNUSED(ind)
Q_UNUSED(zclFrame)
bool result = false;
ResourceItem *srcItem = nullptr;
const auto map = parseParameters.toMap();
enum Op { OpNone, OpLessThan, OpLessEqual, OpEqual, OpGreaterThan, OpGreaterEqual };
Op op = OpNone;
if (!item->parseFunction()) // init on first call
{
if (item->descriptor().type != DataTypeString)
{
return result;
}
if (!map.contains(QLatin1String("to")) || !map.contains(QLatin1String("op")) || !map.contains(QLatin1String("srcitem")))
{
return result;
}
item->setParseFunction(parseNumericToString);
}
ResourceItemDescriptor rid;
if (!getResourceItemDescriptor(map["srcitem"].toString(), rid))
{
return result;
}
srcItem = r->item(rid.suffix);
if (!srcItem)
{
return result;
}
if (!(srcItem->needPushChange() || srcItem->needPushSet()))
{
return result; // only update if needed
}
{
const auto opString = map[QLatin1String("op")].toString();
if (opString == QLatin1String("le")) { op = OpLessEqual; }
else if (opString == QLatin1String("lt")) { op = OpLessThan; }
else if (opString == QLatin1String("eq")) { op = OpEqual; }
else if (opString == QLatin1String("ge")) { op = OpGreaterEqual; }
else if (opString == QLatin1String("gt")) { op = OpGreaterThan; }
else
{
return result;
}
}
const qint64 num = srcItem->toNumber();
const auto to = map["to"].toList();
if (to.size() & 1)
{
return result; // array size must be even
}
auto i = std::find_if(to.cbegin(), to.cend(), [num, op](const QVariant &var)
{
if (var.type() == QVariant::Double || var.type() == QVariant::LongLong)
{
if (op == OpLessEqual) { return num <= var.toInt(); }
if (op == OpLessThan) { return num < var.toInt(); }
if (op == OpEqual) { return num == var.toInt(); }
if (op == OpGreaterEqual) { return num >= var.toInt(); }
if (op == OpGreaterThan) { return num > var.toInt(); }
}
return false;
});
// DBG_Printf(DBG_DDF, "%s/%s numtostr: %s %lld --> %d\n", r->item(RAttrUniqueId)->toCString(), item->descriptor().suffix, srcItem->descriptor().suffix, num, i - to.cbegin());
if (i != to.cend())
{
i++; // point next element (string)
if (i != to.cend() && i->type() == QVariant::String)
{
const QString str = i->toString();
if (!str.isEmpty())
{
DBG_Printf(DBG_DDF, "%s/%s numtostr: %s %lld --> %s\n", r->item(RAttrUniqueId)->toCString(), item->descriptor().suffix, srcItem->descriptor().suffix, num, qPrintable(str));
item->setValue(str);
item->setLastZclReport(srcItem->lastZclReport()); // Treat as report
result = true;
}
}
}
if (result)
{
DeviceJS_ResourceItemValueChanged(item);
}
return result;
}
/*! A generic function to parse ZCL values from read/report commands.
The item->parseParameters() is expected to be an object (given in the device description file).
{"fn": "zcl", "ep": endpoint, "cl": clusterId, "at": attributeId, "mf": manufacturerCode, "eval": expression}
- endpoint: (optional) 255 means any endpoint, 0 means auto selected from the related resource, defaults to 0
- clusterId: string hex value
- attributeId: string hex value or array of string hex values
- manufacturerCode: (optional) string hex value, defaults to "0x0000" for non manufacturer specific commands
- expression: Javascript expression to transform the raw value
Example: { "parse": {"fn": "zcl", "ep:" 1, "cl": "0x0402", "at": "0x0000", "eval": "Attr.val + R.item('config/offset').val" } }
*/
bool parseZclAttribute(Resource *r, ResourceItem *item, const deCONZ::ApsDataIndication &ind, const deCONZ::ZclFrame &zclFrame, const QVariant &parseParameters)
{
bool result = false;
if (!item->parseFunction()) // init on first call
{
Q_ASSERT(!parseParameters.isNull());
if (parseParameters.isNull())
{
return result;
}
ZCL_Param param = getZclParam(parseParameters.toMap());
Q_ASSERT(param.valid);
if (!param.valid)
{
return result;
}
if (param.hasCommandId && param.commandId != zclFrame.commandId())
{
return result;
}
else if (!param.hasCommandId && param.attributeCount == 0)
{
// catch all handler
}
else if (!param.hasCommandId && zclFrame.commandId() != deCONZ::ZclReadAttributesResponseId && zclFrame.commandId() != deCONZ::ZclReportAttributesId)
{
return result;
}
if (param.manufacturerCode != zclFrame.manufacturerCode())
{
return result;
}
if (param.endpoint == AutoEndpoint)
{
param.endpoint = resolveAutoEndpoint(r);
if (param.endpoint == AutoEndpoint)
{
return result;
}
}
item->setParseFunction(parseZclAttribute);
item->setZclProperties(param);
}
const auto &zclParam = item->zclParam();
if (ind.clusterId() != zclParam.clusterId)
{
return result;
}
if (!zclParam.hasCommandId && zclFrame.commandId() != deCONZ::ZclReadAttributesResponseId && zclFrame.commandId() != deCONZ::ZclReportAttributesId)
{
return result;
}
if (zclParam.manufacturerCode != zclFrame.manufacturerCode())
{
return result;
}
if (zclParam.endpoint < BroadcastEndpoint && zclParam.endpoint != ind.srcEndpoint())
{
return result;
}
if (zclParam.attributeCount == 0) // attributes are optional
{
if (zclParam.hasCommandId && zclParam.commandId != zclFrame.commandId())
{
return result;
}
if (evalZclFrame(r, item, ind, zclFrame, parseParameters))
{
result = true;
}
return result;
}
if (zclFrame.payload().isEmpty() && zclParam.attributeCount > 0)
{
return result;
}
QDataStream stream(zclFrame.payload());
stream.setByteOrder(QDataStream::LittleEndian);
while (!stream.atEnd())
{
quint16 attrId;
quint8 status;
quint8 dataType;
stream >> attrId;
if (zclFrame.commandId() == deCONZ::ZclReadAttributesResponseId)
{
stream >> status;
if (status != deCONZ::ZclSuccessStatus)
{
continue;
}
}
stream >> dataType;
deCONZ::ZclAttribute attr(attrId, dataType, QLatin1String(""), deCONZ::ZclReadWrite, true);
if (!attr.readFromStream(stream))
{
break;
}
if (evalZclAttribute(r, item, ind, zclFrame, attr, parseParameters))
{
if (zclFrame.commandId() == deCONZ::ZclReportAttributesId)
{
item->setLastZclReport(deCONZ::steadyTimeRef().ref);
}
result = true;
}
}
return result;
}
/*! A generic function to parse Tuya private cluster values from response/report commands.
The item->parseParameters() is expected to be an object (given in the device description file).
{"fn": "tuya", "dpid": datapointId, "eval": expression}
- datapointId: 1-255 the datapoint identifier (DPID) to extract
- expression: Javascript expression to transform the raw value
Example: { "parse": {"fn": "tuya", "dpid:" 1, "eval": "Attr.val + R.item('config/offset').val" } }
*/
bool parseTuyaData(Resource *r, ResourceItem *item, const deCONZ::ApsDataIndication &ind, const deCONZ::ZclFrame &zclFrame, const QVariant &parseParameters)
{
bool result = false;
if (ind.clusterId() != TUYA_CLUSTER_ID || !(zclFrame.commandId() == TY_DATA_REPORT || zclFrame.commandId() == TY_DATA_RESPONSE))
{
return result;
}
if (!item->parseFunction()) // init on first call
{
const auto map = parseParameters.toMap();
if (map.isEmpty())
{
return result;
}
if (!map.contains(QLatin1String("dpid")) || !map.contains(QLatin1String("eval")))
{
return result;
}
bool ok = false;
ZCL_Param param{};
param.attributes[0] = variantToUint(map.value(QLatin1String("dpid")), 255, &ok);
if (!ok)
{
return result;
}
param.valid = 1;
param.endpoint = ind.srcEndpoint();
param.clusterId = ind.clusterId();
param.attributeCount = 1;
item->setParseFunction(parseTuyaData);
item->setZclProperties(param);
}
quint16 seq;
quint8 dpid;
quint8 dataType;
quint16 dataLength;
quint8 zclDataType = 0;
const auto &zclParam = item->zclParam();
QDataStream stream(zclFrame.payload());
stream.setByteOrder(QDataStream::BigEndian); // tuya is big endian!
stream >> seq;
while (!stream.atEnd()) // a message can contain multiple datapoints
{
stream >> dpid;
stream >> dataType;
stream >> dataLength;
if (stream.status() != QDataStream::Ok)
{
return result;
}
deCONZ::NumericUnion num;
num.u64 = 0;
switch (dataType)
{
case TuyaDataTypeRaw:
case TuyaDataTypeString:
return result; // TODO implement?
case TuyaDataTypeBool:
{ stream >> num.u8; zclDataType = deCONZ::ZclBoolean; }
break;
case TuyaDataTypeEnum:
{ stream >> num.u8; zclDataType = deCONZ::Zcl8BitUint; }
break;
case TuyaDataTypeValue: // docs aren't clear, assume signed
{ stream >> num.s32; zclDataType = deCONZ::Zcl32BitInt; }
break;
case TuyaDataTypeBitmap:
{
switch (dataLength)
{
case 1: { stream >> num.u8; zclDataType = deCONZ::Zcl8BitUint; } break;
case 2: { stream >> num.u16; zclDataType = deCONZ::Zcl16BitUint; } break;
case 4: { stream >> num.u32; zclDataType = deCONZ::Zcl32BitUint; } break;
}
}
break;
default:
return result; // unkown datatype
}
if (dpid == zclParam.attributes[0])
{
// map datapoint into ZCL attribute
deCONZ::ZclAttribute attr(dpid, zclDataType, QLatin1String(""), deCONZ::ZclReadWrite, true);
if (zclDataType == deCONZ::Zcl32BitInt)
{
attr.setValue(qint64(num.s32));
}
else
{
attr.setValue(quint64(num.u32));
}
if (evalZclAttribute(r, item, ind, zclFrame, attr, parseParameters))
{
item->setLastZclReport(deCONZ::steadyTimeRef().ref);
result = true;
}
}
const char *rt = zclFrame.commandId() == TY_DATA_REPORT ? "REPORT" : "RESPONSE";
DBG_Printf(DBG_INFO, "TY_DATA_%s: seq %u, dpid: 0x%02X, type: 0x%02X, length: %u, val: %d\n",
rt, seq, dpid, dataType, dataLength, num.s32);
}
return result;
}
/*! A generic function to trigger Tuya device reporting all datapoints.
Important: This function should be attached to only one item!
The item->readParameters() is expected to be an object (given in the device description file).
{ "fn": "tuya"}
Example: { "read": {"fn": "tuya"} }
*/
static DA_ReadResult readTuyaAllData(const Resource *r, const ResourceItem *item, deCONZ::ApsController *apsCtrl, const QVariant &readParameters)
{
Q_UNUSED(item)
Q_UNUSED(readParameters);
DA_ReadResult result{};
// Workaround: dont't query too quickly, reports will only be send a few seconds after receiving the query command.
// The device report timer resets on each received query.
// Not the ideal solution since this is global across all devices but should do the trick for now.
static deCONZ::SteadyTimeRef lastReadGlobal{};
auto now = deCONZ::steadyTimeRef();
if (now - lastReadGlobal < deCONZ::TimeSeconds{15})
{
return result;
}
lastReadGlobal = now;
auto *rTop = r->parentResource() ? r->parentResource() : r;
const auto *extAddr = rTop->item(RAttrExtAddress);
const auto *nwkAddr = rTop->item(RAttrNwkAddress);
if (!extAddr || !nwkAddr)
{
return result;
}
deCONZ::ApsDataRequest req;
deCONZ::ZclFrame zclFrame;
req.setDstEndpoint(1); // TODO is this always 1? if not search simple descriptor for Tuya cluster
req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
req.setDstAddressMode(deCONZ::ApsNwkAddress);
req.dstAddress().setNwk(nwkAddr->toNumber());
req.dstAddress().setExt(extAddr->toNumber());
req.setClusterId(TUYA_CLUSTER_ID);
req.setProfileId(HA_PROFILE_ID);
req.setSrcEndpoint(1); // TODO
zclFrame.setSequenceNumber(zclNextSequenceNumber());
zclFrame.setCommandId(TY_DATA_QUERY);
zclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |
deCONZ::ZclFCDirectionClientToServer |
deCONZ::ZclFCDisableDefaultResponse);
// no payload
{ // ZCL frame
QDataStream stream(&req.asdu(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
zclFrame.writeToStream(stream);
}
result.isEnqueued = apsCtrl->apsdeDataRequest(req) == deCONZ::Success;
result.apsReqId = req.id();
result.sequenceNumber = zclFrame.sequenceNumber();
result.clusterId = req.clusterId();
return result;
}
/*! A generic function to write Tuya data.
The \p writeParameters is expected to contain one object (given in the device description file).
{ "fn": "tuya", "dpid": datapointId, "dt": dataType, "eval": expression }
- datapointId: number
- dataType: string hex value
bool 0x10
s32 value 0x2b
enum 0x30
8-bit bitmap 0x18
16-bit bitmap 0x19
32-bit bitmap 0x1b
- expression: to transform the item value
Example: "write": {"fn":"tuya", "dpid": 1, "dt": "0x10", "eval": "Item.val == 1"}
*/
bool writeTuyaData(const Resource *r, const ResourceItem *item, deCONZ::ApsController *apsCtrl, const QVariant &writeParameters)
{
Q_ASSERT(r);
Q_ASSERT(item);
Q_ASSERT(apsCtrl);
bool result = false;
const auto rParent = r->parentResource() ? r->parentResource() : r;
const auto *extAddr = rParent->item(RAttrExtAddress);
const auto *nwkAddr = rParent->item(RAttrNwkAddress);
if (!extAddr || !nwkAddr)
{
return result;
}
const auto map = writeParameters.toMap();
if (!map.contains(QLatin1String("dpid")) || !map.contains(QLatin1String("dt")) || !map.contains(QLatin1String("eval")))
{
return result;
}
bool ok = false;
const auto dpid = variantToUint(map.value(QLatin1String("dpid")), 255, &ok);
if (!ok)
{
return result;
}
const auto dataType = variantToUint(map.value("dt"), UINT8_MAX, &ok);
switch (dataType)
{
case deCONZ::ZclBoolean:
case deCONZ::Zcl32BitInt:
case deCONZ::Zcl8BitEnum:
case deCONZ::Zcl8BitBitMap:
case deCONZ::Zcl16BitBitMap:
case deCONZ::Zcl32BitBitMap:
break;
default:
return result; // unsupported datatype
}
const auto expr = map.value("eval").toString();
if (!ok || expr.isEmpty())
{
return result;
}
DBG_Printf(DBG_INFO, "writeTuyaData, dpid: 0x%02X, type: 0x%02X, expr: %s\n",
dpid & 0xFF, dataType & 0xFF, qPrintable(expr));
deCONZ::ApsDataRequest req;
deCONZ::ZclFrame zclFrame;
req.setDstEndpoint(1); // TODO is this always 1? if not search simple descriptor for Tuya cluster
req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
req.setDstAddressMode(deCONZ::ApsNwkAddress);
req.dstAddress().setNwk(nwkAddr->toNumber());
req.dstAddress().setExt(extAddr->toNumber());
req.setClusterId(TUYA_CLUSTER_ID);
req.setProfileId(HA_PROFILE_ID);
req.setSrcEndpoint(1); // TODO
zclFrame.setSequenceNumber(zclNextSequenceNumber());
zclFrame.setCommandId(TY_DATA_REQUEST);
zclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |
deCONZ::ZclFCDirectionClientToServer |
deCONZ::ZclFCDisableDefaultResponse);
{ // payload
QVariant value;
DeviceJs &engine = *DeviceJs::instance();
engine.reset();
engine.setResource(r);
engine.setItem(item);
if (engine.evaluate(expr) == JsEvalResult::Ok)
{
value = engine.result();
DBG_Printf(DBG_INFO, "Tuya write expression: %s --> %s\n", qPrintable(expr), qPrintable(value.toString()));
}
else
{
DBG_Printf(DBG_INFO, "failed to evaluate Tuya write expression for %s/%s: %s, err: %s\n", qPrintable(r->item(RAttrUniqueId)->toString()), item->descriptor().suffix, qPrintable(expr), qPrintable(engine.errorString()));
return result;
}
if (!value.isValid())
{
return result;
}
QDataStream stream(&zclFrame.payload(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::BigEndian); // Tuya is big endian
stream << quint16(req.id()); // use as sequence number
stream << quint8(dpid);
switch (dataType)
{
case deCONZ::ZclBoolean:
{
stream << quint8(TuyaDataTypeBool);
stream << quint16(1); // length
stream << quint8(value.toUInt());
}
break;
case deCONZ::Zcl32BitInt:
{
stream << quint8(TuyaDataTypeValue);
stream << quint16(4); // length
stream << qint32(value.toInt());
}
break;
case deCONZ::Zcl8BitEnum:
{
stream << quint8(TuyaDataTypeEnum);
stream << quint16(1); // length
stream << quint8(value.toUInt());
}
break;
case deCONZ::Zcl8BitBitMap:
{
stream << quint8(TuyaDataTypeBitmap);
stream << quint16(1); // length
stream << quint8(value.toUInt());
}
break;
case deCONZ::Zcl16BitBitMap:
{
stream << quint8(TuyaDataTypeBitmap);
stream << quint16(2); // length
stream << quint16(value.toUInt());
}
break;