forked from u236/homed-service-zigbee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzigbee.cpp
1927 lines (1481 loc) · 74.6 KB
/
zigbee.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
#include <QtEndian>
#include <QEventLoop>
#include <QRandomGenerator>
#include "ezsp.h"
#include "gpio.h"
#include "logger.h"
#include "zcl.h"
#include "zigate.h"
#include "zigbee.h"
#include "zstack.h"
ZigBee::ZigBee(QSettings *config, QObject *parent) : QObject(parent), m_config(config), m_requestTimer(new QTimer(this)), m_neignborsTimer(new QTimer(this)), m_pingTimer(new QTimer(this)), m_statusLedTimer(new QTimer(this)), m_devices(new DeviceList(m_config, this)), m_adapter(nullptr), m_events(QMetaEnum::fromType <Event> ()), m_requestId(0), m_interPanLock(false)
{
m_statusLedPin = m_config->value("gpio/status", "-1").toString();
m_blinkLedPin = m_config->value("gpio/blink", "-1").toString();
m_discovery = m_config->value("default/discovery", true).toBool();
m_cloud = m_config->value("default/cloud", true).toBool();
m_debug = m_config->value("debug/zigbee", false).toBool();
connect(m_devices, &DeviceList::statusUpdated, this, &ZigBee::statusUpdated);
connect(m_devices, &DeviceList::endpointUpdated, this, &ZigBee::endpointUpdated);
connect(m_devices, &DeviceList::pollRequest, this, &ZigBee::pollRequest);
connect(m_statusLedTimer, &QTimer::timeout, this, &ZigBee::updateStatusLed);
GPIO::direction(m_statusLedPin, GPIO::Output);
GPIO::setStatus(m_statusLedPin, m_statusLedPin != m_blinkLedPin);
if (m_statusLedPin == m_blinkLedPin)
return;
GPIO::direction(m_blinkLedPin, GPIO::Output);
GPIO::setStatus(m_blinkLedPin, false);
}
ZigBee::~ZigBee(void)
{
disconnect(m_adapter, &Adapter::permitJoinUpdated, this, &ZigBee::permitJoinUpdated);
m_adapter->setPermitJoin(false);
GPIO::setStatus(m_statusLedPin, false);
GPIO::setStatus(m_blinkLedPin, false);
}
void ZigBee::init(void)
{
QList <QString> list = {"ezsp", "zigate", "znp"};
QString adapterType = m_config->value("zigbee/adapter", "znp").toString();
switch (list.indexOf(adapterType))
{
case 0: m_adapter = new EZSP(m_config, this); break;
case 1: m_adapter = new ZiGate(m_config, this); break;
case 2: m_adapter = new ZStack(m_config, this); break;
default: logWarning << "Unrecognized adapter type" << adapterType; return;
}
connect(m_adapter, &Adapter::adapterReset, this, &ZigBee::adapterReset);
connect(m_adapter, &Adapter::coordinatorReady, this, &ZigBee::coordinatorReady);
connect(m_adapter, &Adapter::permitJoinUpdated, this, &ZigBee::permitJoinUpdated);
connect(m_adapter, &Adapter::requestFinished, this, &ZigBee::requestFinished);
m_devices->init();
m_adapter->init();
}
void ZigBee::setPermitJoin(bool enabled)
{
if (!m_adapter)
return;
m_adapter->setPermitJoin(enabled);
}
void ZigBee::togglePermitJoin(void)
{
if (!m_adapter)
return;
m_adapter->togglePermitJoin();
}
void ZigBee::updateDevice(const QString &deviceName, const QString &name, bool active, bool discovery, bool cloud)
{
Device device = m_devices->byName(deviceName), other = m_devices->byName(name);
bool check = false;
if (device.isNull() || device->removed() || device->logicalType() == LogicalType::Coordinator)
return;
if (device != other && !other.isNull() && !other->removed())
{
logWarning << "Device" << device->name() << "rename failed, name already in use";
emit deviceEvent(device.data(), Event::deviceNameDuplicate);
return;
}
else if (device->name() != name)
{
emit deviceEvent(device.data(), Event::deviceAboutToRename);
if (!other.isNull() && other->removed())
m_devices->remove(other->ieeeAddress());
device->setName(name.isEmpty() ? device->ieeeAddress().toHex(':') : name.trimmed());
check = true;
}
if (device->active() != active)
{
device->setAvailability(active ? Availability::Unknown : Availability::Inactive);
device->setActive(active);
check = true;
}
if (device->discovery() != discovery || device->cloud() != cloud)
{
device->setDiscovery(discovery);
device->setCloud(cloud);
check = true;
}
if (check)
{
emit deviceEvent(device.data(), Event::deviceUpdated);
m_devices->storeDatabase();
}
}
void ZigBee::removeDevice(const QString &deviceName, bool force)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || device->logicalType() == LogicalType::Coordinator)
return;
if (!force)
{
enqueueRequest(device, RequestType::Leave);
return;
}
logInfo << "Device" << device->name() << "removed (force)";
emit deviceEvent(device.data(), Event::deviceRemoved);
m_devices->removeDevice(device);
m_devices->storeDatabase();
}
void ZigBee::setupDevice(const QString &deviceName, bool reportings)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
m_devices->setupDevice(device);
emit deviceEvent(device.data(), Event::deviceUpdated);
if (!reportings)
{
logInfo << "Device" << device->name() << "configuration updated without reportings";
return;
}
if (!configureDevice(device))
{
logWarning << "Device" << device->name() << "configuration failed";
return;
}
logInfo << "Device" << device->name() << "configuration updated";
}
void ZigBee::setupReporting(const QString &deviceName, quint8 endpointId, const QString &reportingName, quint16 minInterval, quint16 maxInterval, quint16 valueChange)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
{
if (endpointId && it.key() != endpointId)
continue;
for (int i = 0; i < it.value()->bindings().count(); i++)
if (!bindRequest(device, it.value()->id(), it.value()->bindings().at(i)->clusterId()))
return;
for (int i = 0; i < it.value()->reportings().count(); i++)
{
const Reporting &reporting = it.value()->reportings().at(i);
if (!reportingName.isEmpty() && reporting->name() != reportingName)
continue;
if (minInterval)
reporting->setMinInterval(minInterval);
if (maxInterval)
reporting->setMaxInterval(maxInterval);
if (valueChange)
reporting->setValueChange(valueChange);
configureReporting(device, it.value()->id(), reporting);
}
}
}
void ZigBee::bindingControl(const QString &deviceName, quint8 endpointId, quint16 clusterId, const QVariant &dstName, quint8 dstEndpointId, bool unbind)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
switch (dstName.type())
{
case QVariant::LongLong:
{
quint16 value = qToLittleEndian <quint16> (dstName.toInt());
if (value)
bindRequest(device, endpointId, clusterId, QByteArray(reinterpret_cast <char*> (&value), sizeof(value)), 0xFF, unbind);
break;
}
case QVariant::String:
{
Device destination = m_devices->byName(dstName.toString());
if (!destination.isNull() && !destination->removed() && destination->active())
bindRequest(device, endpointId, clusterId, destination->ieeeAddress(), dstEndpointId, unbind);
break;
}
default:
break;
}
}
void ZigBee::groupControl(const QString &deviceName, quint8 endpointId, quint16 groupId, bool remove)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
groupId = qFromLittleEndian(groupId);
enqueueRequest(device, endpointId ? endpointId : 0x01, CLUSTER_GROUPS, zclHeader(FC_CLUSTER_SPECIFIC, m_requestId, remove ? 0x03 : 0x00).append(reinterpret_cast <char*> (&groupId), sizeof(groupId)).append(remove ? 0 : 1, 0x00), QString("%1 group request").arg(remove ? "remove" : "add"));
}
void ZigBee::removeAllGroups(const QString &deviceName, quint8 endpointId)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
enqueueRequest(device, endpointId ? endpointId : 0x01, CLUSTER_GROUPS, zclHeader(FC_CLUSTER_SPECIFIC, m_requestId, 0x04), QString("remove all groups request"));
}
void ZigBee::otaUpgrade(const QString &deviceName, quint8 endpointId, const QString &fileName, bool force)
{
Device device = m_devices->byName(deviceName);
otaImageNotifyStruct payload;
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator || fileName.isEmpty() || !QFile::exists(fileName))
return;
m_otaUpgradeFile = fileName;
m_otaForce = force;
payload.type = 0x00;
payload.jitter = 0x64; // TODO: check this
logInfo << "Device" << device->name() << "OTA upgrade notification enqueued";
enqueueRequest(device, endpointId ? endpointId : 0x01, CLUSTER_OTA_UPGRADE, zclHeader(FC_CLUSTER_SPECIFIC | FC_SERVER_TO_CLIENT, m_requestId, 0x00).append(reinterpret_cast <char*> (&payload), sizeof(payload)));
}
void ZigBee::getProperties(const QString &deviceName)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
{
if (it.value()->properties().isEmpty())
continue;
emit endpointUpdated(device.data(), it.key());
}
}
void ZigBee::clusterRequest(const QString &deviceName, quint8 endpointId, quint16 clusterId, quint16 manufacturerCode, quint8 commandId, const QByteArray &payload, bool global)
{
Device device = m_devices->byName(deviceName);
QByteArray request;
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
request = zclHeader(global ? 0x00 : FC_CLUSTER_SPECIFIC, m_requestId, commandId, manufacturerCode).append(payload);
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId ? endpointId : 0x01) << "cluster" << QString::asprintf("0x%04x", clusterId) << "request" << m_requestId << "enqueued with data" << request.toHex(':');
enqueueRequest(device, endpointId ? endpointId : 0x01, clusterId, request, QString("request %1").arg(m_requestId), true);
}
void ZigBee::touchLinkRequest(const QByteArray &ieeeAddress, quint8 channel, bool reset)
{
if (m_interPanLock)
return;
m_interPanLock = true;
if (reset)
touchLinkReset(ieeeAddress, channel);
else
touchLinkScan();
m_adapter->resetInterPanChannel();
if (!m_requests.isEmpty())
m_requestTimer->start();
m_interPanLock = false;
}
void ZigBee::deviceAction(const QString &deviceName, quint8 endpointId, const QString &name, const QVariant &data)
{
Device device = m_devices->byName(deviceName);
if (device.isNull() || device->removed() || !device->active() || device->logicalType() == LogicalType::Coordinator)
return;
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
{
if (endpointId && it.key() != endpointId)
continue;
for (int i = 0; i < it.value()->actions().count(); i++)
{
const Action &action = it.value()->actions().at(i);
if (action->name() == name || action->name() == "tuyaDataPoints" || action->actions().contains(name))
{
QByteArray request = action->request(name, data);
if (request.isEmpty())
continue;
if (data.type() != QVariant::String || !data.toString().isEmpty())
enqueueRequest(device, it.key(), action->clusterId(), request, QString("%1 action request").arg(name), false, action->manufacturerCode(), action->attributes());
break;
}
}
}
}
void ZigBee::groupAction(quint16 groupId, const QString &name, const QVariant &data)
{
int type = QMetaType::type(QString(name).append("Action").toUtf8());
if (type)
{
Action action(reinterpret_cast <ActionObject*> (QMetaType::create(type)));
QByteArray request = action->request(name, data);
if (request.isEmpty() || (data.type() == QVariant::String && data.toString().isEmpty()))
return;
if (!m_adapter->multicastRequest(m_requestId, groupId, 0x01, 0xFF, action->clusterId(), request))
{
logWarning << "Group" << groupId << action->name().toUtf8().constData() << "action request aborted";
return;
}
logInfo << "Group" << groupId << action->name().toUtf8().constData() << "action request sent";
}
}
void ZigBee::enqueueRequest(const Device &device, quint8 endpointId, quint16 clusterId, const QByteArray &data, const QString &name, bool debug, quint16 manufacturerCode, const QList <quint16> &attributes)
{
DataRequest request(new DataRequestObject(device, endpointId, clusterId, data, name, debug, manufacturerCode, attributes));
if (!m_requestTimer->isActive() && !m_interPanLock)
m_requestTimer->start();
m_requests.insert(m_requestId++, Request(new RequestObject(QVariant::fromValue(request), RequestType::Data)));
}
void ZigBee::enqueueRequest(const Device &device, RequestType type)
{
if (!m_requestTimer->isActive() && !m_interPanLock)
m_requestTimer->start();
m_requests.insert(m_requestId++, Request(new RequestObject(QVariant::fromValue(device), type)));
}
bool ZigBee::interviewRequest(quint8 id, const Device &device)
{
m_adapter->setRequestParameters(device->ieeeAddress(), device->batteryPowered());
if (device->manufacturerName().isEmpty() || device->modelName().isEmpty())
{
if (!device->descriptorReceived())
{
if (m_adapter->zdoRequest(id, device->networkAddress(), ZDO_NODE_DESCRIPTOR_REQUEST))
return true;
interviewError(device, "node descriptor request failed");
return false;
}
if (!device->endpointsReceived())
{
if (m_adapter->zdoRequest(id, device->networkAddress(), ZDO_ACTIVE_ENDPOINTS_REQUEST))
return true;
interviewError(device, "active endpoints request failed");
return false;
}
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
{
if (!it.value()->descriptorReceived())
{
device->setInterviewEndpointId(it.key());
if (m_adapter->zdoRequest(id, device->networkAddress(), ZDO_SIMPLE_DESCRIPTOR_REQUEST, QByteArray(1, static_cast <char> (it.key()))))
return true;
interviewError(device, QString::asprintf("endpoint 0x%02x simple descriptor request failed", it.key()));
return false;
}
}
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
{
if (it.value()->inClusters().contains(CLUSTER_BASIC))
{
if (m_adapter->unicastRequest(id, device->networkAddress(), 0x01, it.key(), CLUSTER_BASIC, readAttributesRequest(id, 0x0000, {0x0001, 0x0004, 0x0005, 0x0007, 0x4000})))
return true;
interviewError(device, "read basic attributes request failed");
return false;
}
}
interviewError(device, "device has empty manufacturer name or model name");
return false;
}
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
{
if (!device->batteryPowered() && it.value()->inClusters().contains(CLUSTER_COLOR_CONTROL) && !it.value()->colorCapabilities())
{
if (m_adapter->unicastRequest(id, device->networkAddress(), 0x01, it.key(), CLUSTER_COLOR_CONTROL, readAttributesRequest(id, 0x0000, {0x400A})))
return true;
interviewError(device, "read color capabilities request failed");
return false;
}
if (!it.value()->inClusters().contains(CLUSTER_IAS_ZONE))
continue;
switch (it.value()->zoneStatus())
{
case ZoneStatus::Unknown:
{
if (m_adapter->unicastRequest(id, device->networkAddress(), 0x01, it.key(), CLUSTER_IAS_ZONE, readAttributesRequest(id, 0x0000, {0x0000, 0x0001, 0x0010})))
return true;
interviewError(device, "read current IAS zone status request failed");
return false;
}
case ZoneStatus::SetAddress:
{
quint64 ieeeAddress;
memcpy(&ieeeAddress, m_adapter->ieeeAddress().constData(), sizeof(ieeeAddress));
ieeeAddress = qToLittleEndian(qFromBigEndian(ieeeAddress));
if (m_adapter->unicastRequest(id, device->networkAddress(), 0x01, it.key(), CLUSTER_IAS_ZONE, writeAttributeRequest(id, 0x0000, 0x0010, DATA_TYPE_IEEE_ADDRESS, QByteArray(reinterpret_cast <char*> (&ieeeAddress), sizeof(ieeeAddress)))))
return true;
interviewError(device, "write IAS zone CIE address request failed");
return false;
}
case ZoneStatus::Enroll:
{
iasZoneEnrollResponseStruct payload;
payload.responseCode = 0x00;
payload.zoneId = IAS_ZONE_ID;
m_adapter->unicastRequest(id, device->networkAddress(), 0x01, it.key(), CLUSTER_IAS_ZONE, zclHeader(FC_CLUSTER_SPECIFIC | FC_DISABLE_DEFAULT_RESPONSE, id, 0x00).append(reinterpret_cast <char*> (&payload), sizeof(payload)));
m_adapter->unicastRequest(id, device->networkAddress(), 0x01, it.key(), CLUSTER_IAS_ZONE, readAttributesRequest(id, 0x0000, {0x0000, 0x0010}));
break;
}
case ZoneStatus::Enrolled:
{
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", it.key()) << "IAS zone enrolled";
break;
}
}
}
interviewFinished(device);
return true;
}
bool ZigBee::interviewQuirks(const Device &device)
{
if (device->options().value("ikeaCover").toBool())
{
QList <QString> list = device->firmware().split('.');
if (list.value(0).toInt() >= 24)
{
quint32 value = qToLittleEndian <quint32> (172800);
enqueueRequest(device, 0x01, CLUSTER_POLL_CONTROL, writeAttributeRequest(m_requestId, 0x0000, 0x0000, DATA_TYPE_32BIT_UNSIGNED, QByteArray(reinterpret_cast <char*> (&value), sizeof(value))), "polling configuration request");
}
}
if (device->options().value("ikeaRemote").toBool())
{
QList <QString> list = device->firmware().split('.');
quint16 groupId = qToLittleEndian <quint16> (IKEA_GROUP);
bool check = list.value(0).toInt() < 2 || (list.value(0).toInt() == 2 && list.value(1).toInt() < 3) || (list.value(0).toInt() == 2 && list.value(1).toInt() == 3 && list.value(2).toInt() < 75);
if ((check && !bindRequest(device, 0x01, CLUSTER_ON_OFF, QByteArray(reinterpret_cast <char*> (&groupId), sizeof(groupId)), 0xFF)) || (!check && !bindRequest(device, 0x01, CLUSTER_ON_OFF)))
return false;
}
if (device->manufacturerName() == "IKEA of Sweden" && device->powerSource() == POWER_SOURCE_BATTERY)
enqueueRequest(device, 0x01, CLUSTER_POWER_CONFIGURATION, readAttributesRequest(m_requestId, 0x0000, {0x0021}), "battery percentage request");
if (device->manufacturerName() == "LUMI" && device->modelName() == "lumi.switch.n3acn3") // TODO: make it optional?
enqueueRequest(device, 0x01, CLUSTER_LUMI, writeAttributeRequest(m_requestId, MANUFACTURER_CODE_LUMI, 0x0200, DATA_TYPE_8BIT_UNSIGNED, QByteArray(1, 0x01)), "magic request");
if (device->options().value("tuyaMagic").toBool())
enqueueRequest(device, 0x01, CLUSTER_BASIC, readAttributesRequest(m_requestId, 0x0000, {0x0004, 0x0000, 0x0001, 0x0005, 0x0007, 0xFFFE}), "magic request");
if (device->options().value("tuyaDataQuery").toBool())
enqueueRequest(device, 0x01, CLUSTER_TUYA_DATA, zclHeader(FC_CLUSTER_SPECIFIC, m_requestId, 0x03), "data query request");
return true;
}
void ZigBee::interviewDevice(const Device &device)
{
if (device->interviewFinished())
return;
connect(device->timer(), &QTimer::timeout, this, &ZigBee::interviewTimeout, Qt::UniqueConnection);
device->timer()->setSingleShot(true);
device->timer()->start(DEVICE_INTERVIEW_TIMEOUT);
enqueueRequest(device, RequestType::Interview);
}
void ZigBee::interviewFinished(const Device &device)
{
device->timer()->stop();
if (device->interviewFinished()) // TODO: figure out reasons for multiple interviewFinished calls
return;
logInfo << "Device" << device->name() << "manufacturer name is" << device->manufacturerName() << "and model name is" << device->modelName();
m_devices->setupDevice(device);
if (!device->firmware().isEmpty())
logInfo << "Device" << device->name() << "firmware is" << device->firmware();
if (!device->description().isEmpty())
logInfo << "Device" << device->name() << "identified as" << device->description();
if (!interviewQuirks(device) || !configureDevice(device))
{
logWarning << "Device" << device->name() << "interview finished with errors";
emit deviceEvent(device.data(), Event::interviewError);
}
else
{
logInfo << "Device" << device->name() << "interview finished successfully";
emit deviceEvent(device.data(), Event::interviewFinished);
device->setInterviewFinished();
}
m_devices->storeDatabase();
}
void ZigBee::interviewError(const Device &device, const QString &reason)
{
if (!device->timer()->isActive())
return;
logWarning << "Device" << device->name() << "interview error:" << reason;
emit deviceEvent(device.data(), Event::interviewError);
device->timer()->stop();
}
bool ZigBee::bindRequest(const Device &device, quint8 endpointId, quint16 clusterId, const QByteArray &address, quint8 dstEndpointId, bool unbind)
{
m_adapter->setRequestParameters(device->ieeeAddress(), device->batteryPowered());
m_replyId = m_requestId;
m_replyReceived = false;
if (!m_adapter->bindRequest(m_requestId, device->networkAddress(), endpointId, clusterId, address, dstEndpointId, unbind))
{
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << "cluster" << QString::asprintf("0x%04x", clusterId) << (unbind ? "unbinding" : "binding") << "request aborted";
return false;
}
if (!m_replyReceived && !m_adapter->waitForSignal(this, SIGNAL(replyReceived()), NETWORK_REQUEST_TIMEOUT))
{
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << "cluster" << QString::asprintf("0x%04x", clusterId) << (unbind ? "unbinding" : "binding") << "timed out";
return false;
}
m_requestId++;
if (m_requestStatus)
{
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << "cluster" << QString::asprintf("0x%04x", clusterId) << (unbind ? "unbinding" : "binding") << "failed, status code:" << QString::asprintf("0x%02x", m_requestStatus);
return false;
}
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << "cluster" << QString::asprintf("0x%04x", clusterId) << (unbind ? "unbinding" : "binding") << "finished successfully";
return true;
}
bool ZigBee::configureReporting(const Device &device, quint8 endpointId, const Reporting &reporting)
{
QMap <QString, QVariant> options = device->options().value(device->options().contains("reporting") ? "reporting" : QString(reporting->name()).append("Reporting")).toMap();
QByteArray request = zclHeader(0x00, m_requestId, CMD_CONFIGURE_REPORTING);
for (int i = 0; i < reporting->attributes().count(); i++)
{
configureReportingStruct item;
item.direction = 0x00;
item.attributeId = qToLittleEndian(reporting->attributes().at(i));
item.dataType = reporting->dataType();
item.minInterval = qToLittleEndian <quint16> (options.contains("minInterval") ? options.value("minInterval").toInt() : reporting->minInterval());
item.maxInterval = qToLittleEndian <quint16> (options.contains("maxInterval") ? options.value("maxInterval").toInt() : reporting->maxInterval());
item.valueChange = qToLittleEndian <quint16> (options.contains("valueChange") ? options.value("valueChange").toInt() : reporting->valueChange());
request.append(reinterpret_cast <char*> (&item), sizeof(item) - sizeof(item.valueChange) + zclDataSize(item.dataType));
}
m_adapter->setRequestParameters(device->ieeeAddress(), device->batteryPowered());
m_replyId = m_requestId;
m_replyReceived = false;
if (!m_adapter->unicastRequest(m_requestId, device->networkAddress(), 0x01, endpointId, reporting->clusterId(), request))
{
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << reporting->name().toUtf8().constData() << "reporting configuration request aborted";
return false;
}
if (!m_replyReceived && !m_adapter->waitForSignal(this, SIGNAL(replyReceived()), NETWORK_REQUEST_TIMEOUT))
{
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << reporting->name().toUtf8().constData() << "reporting configuration request timed out";
return false;
}
m_requestId++;
if (m_requestStatus)
{
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << reporting->name().toUtf8().constData() << "reporting configuration request failed, status code:" << QString::asprintf("0x%02x", m_requestStatus);
return false;
}
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpointId) << reporting->name().toUtf8().constData() << "reporting configuration request finished successfully";
return true;
}
bool ZigBee::configureDevice(const Device &device)
{
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
for (int i = 0; i < it.value()->bindings().count(); i++)
if (!bindRequest(device, it.value()->id(), it.value()->bindings().at(i)->clusterId()))
return false;
for (auto it = device->endpoints().begin(); it != device->endpoints().end(); it++)
for (int i = 0; i < it.value()->reportings().count(); i++)
if (!configureReporting(device, it.value()->id(), it.value()->reportings().at(i)))
return false;
return true;
}
void ZigBee::parseAttribute(const Endpoint &endpoint, quint16 clusterId, quint8 transactionId, quint16 attributeId, quint8 dataType, const QByteArray &data)
{
Device device = endpoint->device();
bool check = false;
if (m_debug)
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "cluster" << QString::asprintf("0x%04x", clusterId) << "attribute" << QString::asprintf("0x%04x", attributeId) << "report received with type" << QString::asprintf("0x%02x", dataType) << "and data" << (data.isEmpty() ? "(empty)" : data.toHex(':')) << "and transaction id" << transactionId;
if (clusterId == CLUSTER_BASIC && attributeId <= 0x4000)
{
switch (attributeId)
{
case 0x0001:
if (dataType != DATA_TYPE_8BIT_UNSIGNED)
return;
device->setVersion(static_cast <quint8> (data.at(0)));
break;
case 0x0004:
if (dataType != DATA_TYPE_CHARACTER_STRING)
return;
device->setManufacturerName(data != "\u0002KE" ? QString(data).trimmed() : "IKEA of Sweden");
break;
case 0x0005:
if (dataType != DATA_TYPE_CHARACTER_STRING)
return;
device->setModelName(QString(data).trimmed());
break;
case 0x0007:
if (dataType != DATA_TYPE_8BIT_UNSIGNED && dataType != DATA_TYPE_8BIT_ENUM)
return;
device->setPowerSource(static_cast <quint8> (data.at(0)));
break;
case 0x4000:
if (dataType != DATA_TYPE_CHARACTER_STRING)
return;
device->setFirmware(QString(data).trimmed());
break;
}
if (!device->interviewFinished() && !device->manufacturerName().isEmpty() && !device->modelName().isEmpty() && (attributeId == 0x0004 || attributeId == 0x0005))
interviewDevice(device);
return;
}
if (clusterId == CLUSTER_COLOR_CONTROL && attributeId == 0x400A)
{
quint16 value = 0xFFFF;
if (dataType == DATA_TYPE_16BIT_BITMAP)
{
memcpy(&value, data.constData(), data.length());
value = qFromLittleEndian(value);
}
endpoint->setColorCapabilities(value);
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "color capabilities:" << QString::asprintf("0x%04x", endpoint->colorCapabilities());
interviewDevice(device);
return;
}
if (clusterId == CLUSTER_IAS_ZONE)
{
if (attributeId == 0x0010 && dataType == DATA_TYPE_NO_DATA) // TODO: figure it out
{
endpoint->setZoneStatus(ZoneStatus::Enrolled);
interviewDevice(device);
return;
}
switch (attributeId)
{
case 0x0000:
{
if (dataType != DATA_TYPE_8BIT_ENUM)
return;
endpoint->setZoneStatus(data.at(0) ? ZoneStatus::Enrolled : ZoneStatus::Enroll);
return;
}
case 0x0001:
{
quint16 value;
if (dataType != DATA_TYPE_16BIT_ENUM)
return;
memcpy(&value, data.constData(), data.length());
endpoint->setZoneType(qFromLittleEndian(value));
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "IAS zone type:" << QString::asprintf("0x%04x", endpoint->zoneType());
return;
}
case 0x0010:
{
quint64 ieeeAddress;
if (dataType != DATA_TYPE_IEEE_ADDRESS)
return;
memcpy(&ieeeAddress, m_adapter->ieeeAddress().constData(), sizeof(ieeeAddress));
ieeeAddress = qToLittleEndian(qFromBigEndian(ieeeAddress));
if (memcmp(&ieeeAddress, data.constData(), sizeof(ieeeAddress)))
endpoint->setZoneStatus(ZoneStatus::SetAddress);
interviewDevice(device);
return;
}
}
}
if (!device->interviewFinished())
return;
if (clusterId == CLUSTER_TIME && device->manufacturerName() == "www.efektalab.com")
{
QDateTime now = QDateTime::currentDateTime();
quint32 value = qToLittleEndian <quint32> (now.toTime_t() + now.offsetFromUtc() - TIME_OFFSET);
if (m_debug)
logInfo << "Device" << device->name() << "requested Efekta time synchronization";
enqueueRequest(device, endpoint->id(), CLUSTER_TIME, writeAttributeRequest(m_requestId, 0x0000, 0x0000, DATA_TYPE_UTC_TIME, QByteArray(reinterpret_cast <char*> (&value), sizeof(value))));
return;
}
for (int i = 0; i < endpoint->properties().count(); i++)
{
const Property &property = endpoint->properties().at(i);
if (property->clusters().contains(clusterId))
{
QVariant value = property->value();
if (device->options().value("checkTransactionId").toBool() && property->transactionId() == transactionId)
continue;
property->setTransactionId(transactionId);
property->parseAttribte(clusterId, attributeId, data);
check = true;
if (property->timeout())
property->setTime(QDateTime::currentSecsSinceEpoch());
if (property->value() == value)
continue;
endpoint->setUpdated(true);
}
}
if (!m_debug || check)
return;
logWarning << "No property found for device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "cluster" << QString::asprintf("0x%04x", clusterId) << "attribute" << QString::asprintf("0x%04x", attributeId) << "report with type" << QString::asprintf("0x%02x", dataType) << "and data" << (data.isEmpty() ? "(empty)" : data.toHex(':'));
}
void ZigBee::clusterCommandReceived(const Endpoint &endpoint, quint16 clusterId, quint16 manufacturerCode, quint8 transactionId, quint8 commandId, const QByteArray &payload)
{
Device device = endpoint->device();
bool check = false;
if (m_debug)
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "cluster" << QString::asprintf("0x%04x", clusterId) << "command" << QString::asprintf("0x%02x", commandId) << "received with payload" << (payload.isEmpty() ? "(empty)" : payload.toHex(':')) << "and transaction id" << transactionId;
if (clusterId == CLUSTER_IDENTIFY)
return;
if (clusterId == CLUSTER_GROUPS)
{
switch (commandId)
{
case 0x00:
case 0x03:
{
const groupControlResponseStruct *response = reinterpret_cast <const groupControlResponseStruct*> (payload.constData());
switch (response->status)
{
case STATUS_SUCCESS:
logInfo << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "group" << qFromLittleEndian(response->groupId) << "successfully" << (commandId ? "removed" : "added");
break;
case STATUS_INSUFFICIENT_SPACE:
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "group" << qFromLittleEndian(response->groupId) << "not added, no free space available";
break;
case STATUS_DUPLICATE_EXISTS:
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "group" << qFromLittleEndian(response->groupId) << "already exists";
break;
case STATUS_NOT_FOUND:
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "group" << qFromLittleEndian(response->groupId) << "not found";
break;
default:
logWarning << "Device" << device->name() << "endpoint" << QString::asprintf("0x%02x", endpoint->id()) << "group" << qFromLittleEndian(response->groupId) << (commandId ? "remove" : "add") << "command status" << QString::asprintf("0x%02x", response->status) << "unrecognized";
break;
}
break;
}
default:
logWarning << "Unrecognized group control command" << QString::asprintf("0x%02x", commandId) << "received from device" << device->name() << "with payload:" << (payload.isEmpty() ? "(empty)" : payload.toHex(':'));
break;
}
return;
}
if (clusterId == CLUSTER_OTA_UPGRADE)
{
QFile file(m_otaUpgradeFile);
otaFileHeaderStruct header;
memset(&header, 0, sizeof(header));
if (file.exists() && file.open(QFile::ReadOnly))
memcpy(&header, file.read(sizeof(header)).constData(), sizeof(header));
switch (commandId)
{
case 0x01:
{
const otaNextImageRequestStruct *request = reinterpret_cast <const otaNextImageRequestStruct*> (payload.constData());
otaNextImageResponseStruct response;
if (!file.isOpen() || (!m_otaForce && (request->manufacturerCode != header.manufacturerCode || request->imageType != header.imageType)))
{
if (!file.fileName().isEmpty())
logWarning << "Device" << device->name() << "OTA upgrade image request failed, file open error or header data mismatch request data";
enqueueRequest(device, endpoint->id(), CLUSTER_OTA_UPGRADE, zclHeader(FC_CLUSTER_SPECIFIC | FC_SERVER_TO_CLIENT | FC_DISABLE_DEFAULT_RESPONSE, transactionId, 0x02, manufacturerCode).append(STATUS_NO_IMAGE_AVAILABLE));
m_otaUpgradeFile.clear();
break;
}
if (request->fileVersion == header.fileVersion)
{
logWarning << "Device" << device->name() << "OTA upgrade not started, version match:" << QString::asprintf("0x%08x", qFromLittleEndian(request->fileVersion)).toUtf8().constData();
enqueueRequest(device, endpoint->id(), CLUSTER_OTA_UPGRADE, zclHeader(FC_CLUSTER_SPECIFIC | FC_SERVER_TO_CLIENT | FC_DISABLE_DEFAULT_RESPONSE, transactionId, 0x02, manufacturerCode).append(STATUS_NO_IMAGE_AVAILABLE));
m_otaUpgradeFile.clear();
break;
}
logInfo << "Device" << device->name() << "OTA upgrade started...";
response.status = 0x00;
response.manufacturerCode = m_otaForce ? request->manufacturerCode : header.manufacturerCode;
response.imageType = m_otaForce ? request->imageType : header.imageType;
response.fileVersion = header.fileVersion;
response.imageSize = header.imageSize;
enqueueRequest(device, endpoint->id(), CLUSTER_OTA_UPGRADE, zclHeader(FC_CLUSTER_SPECIFIC | FC_SERVER_TO_CLIENT | FC_DISABLE_DEFAULT_RESPONSE, transactionId, 0x02, manufacturerCode).append(reinterpret_cast <char*> (&response), sizeof(response)));
break;
}
case 0x03:
{
const otaImageBlockRequestStruct *request = reinterpret_cast <const otaImageBlockRequestStruct*> (payload.constData());
otaImageBlockResponseStruct response;
QByteArray block;
if (!file.isOpen() || (!m_otaForce && (request->manufacturerCode != header.manufacturerCode || request->imageType != header.imageType || request->fileVersion != header.fileVersion)))
{
logWarning << "Device" << device->name() << "OTA upgrade block request failed, file open error or header data mismatch request data";
enqueueRequest(device, endpoint->id(), CLUSTER_OTA_UPGRADE, zclHeader(FC_CLUSTER_SPECIFIC | FC_SERVER_TO_CLIENT | FC_DISABLE_DEFAULT_RESPONSE, transactionId, 0x05, manufacturerCode).append(STATUS_NO_IMAGE_AVAILABLE));
m_otaUpgradeFile.clear();
break;
}
file.seek(qFromLittleEndian(request->fileOffset));
block = file.read(request->maxDataSize);
logInfo << "Device" << device->name() << "OTA upgrade progress is" << QString::asprintf("%.2f%%", static_cast <double> (file.pos() + block.size()) / file.size() * 100).toUtf8().constData();
response.status = 0x00;
response.manufacturerCode = request->manufacturerCode;