forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 8
/
device.cpp
2557 lines (2238 loc) · 78.6 KB
/
device.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 <QBasicTimer>
#include <QElapsedTimer>
#include <QTimer>
#include <QTimerEvent>
#include <QMetaObject>
#include <array>
#include <deconz/dbg_trace.h>
#include <deconz/node.h>
#include "device.h"
#include "device_access_fn.h"
#include "device_descriptions.h"
#include "event.h"
#include "event_emitter.h"
#include "utils/utils.h"
#include "zcl/zcl.h"
#include "zdp/zdp.h"
#define STATE_LEVEL_BINDING StateLevel1
#define STATE_LEVEL_POLL StateLevel2
#define MGMT_BIND_SUPPORT_UNKNOWN -1
#define MGMT_BIND_SUPPORTED 1
#define MGMT_BIND_NOT_SUPPORTED 0
#define DEV_INVALID_DEVICE_ID -1
typedef void (*DeviceStateHandler)(Device *, const Event &);
/*! Device state machine description can be found in the wiki:
https://github.com/dresden-elektronik/deconz-rest-plugin-v2/wiki/Device-Class#state-machine
*/
void DEV_InitStateHandler(Device *device, const Event &event);
void DEV_IdleStateHandler(Device *device, const Event &event);
void DEV_NodeDescriptorStateHandler(Device *device, const Event &event);
void DEV_ActiveEndpointsStateHandler(Device *device, const Event &event);
void DEV_SimpleDescriptorStateHandler(Device *device, const Event &event);
void DEV_BasicClusterStateHandler(Device *device, const Event &event);
void DEV_GetDeviceDescriptionHandler(Device *device, const Event &event);
static const deCONZ::SimpleDescriptor *DEV_GetSimpleDescriptorForServerCluster(const Device *device, deCONZ::ZclClusterId_t clusterId);
void DEV_BindingHandler(Device *device, const Event &event);
void DEV_BindingTableReadHandler(Device *device, const Event &event);
void DEV_BindingTableVerifyHandler(Device *device, const Event &event);
void DEV_BindingCreateHandler(Device *device, const Event &event);
void DEV_BindingRemoveHandler(Device *device, const Event &event);
void DEV_ReadReportConfigurationHandler(Device *device, const Event &event);
void DEV_ReadNextReportConfigurationHandler(Device *device, const Event &event);
void DEV_ConfigureNextReportConfigurationHandler(Device *device, const Event &event);
void DEV_ConfigureReportingHandler(Device *device, const Event &event);
void DEV_BindingIdleHandler(Device *device, const Event &event);
void DEV_PollIdleStateHandler(Device *device, const Event &event);
void DEV_PollNextStateHandler(Device *device, const Event &event);
void DEV_PollBusyStateHandler(Device *device, const Event &event);
void DEV_DeadStateHandler(Device *device, const Event &event);
// enable domain specific string literals
using namespace deCONZ::literals;
constexpr int RxOnWhenIdleResponseTime = 2000; // Expect shorter response delay for rxOnWhenIdle devices
constexpr int RxOffWhenIdleResponseTime = 8000; // 7680 ms + some space for timeout
constexpr int MaxConfirmTimeout = 20000; // If for some reason no APS-DATA.confirm is received (should almost
constexpr int BindingAutoCheckInterval = 1000 * 60 * 60;
constexpr int MaxPollItemRetries = 3;
constexpr int MaxIdleApsConfirmErrors = 16;
constexpr int MaxSubResources = 8;
static int devManaged = -1;
struct DEV_PollItem
{
explicit DEV_PollItem(const Resource *r, const ResourceItem *i, const QVariant &p) :
resource(r), item(i), readParameters(p) {}
size_t retry = 0;
const Resource *resource = nullptr;
const ResourceItem *item = nullptr;
QVariant readParameters;
};
// special value for ReportTracker::lastConfigureCheck during zcl configure reporting step
constexpr int64_t MarkZclConfigureBusy = 21;
struct ReportTracker
{
deCONZ::SteadyTimeRef lastReport;
deCONZ::SteadyTimeRef lastConfigureCheck;
uint16_t clusterId = 0;
uint16_t attributeId = 0;
uint8_t endpoint = 0;
};
struct BindingTracker
{
deCONZ::SteadyTimeRef tBound;
};
struct BindingContext
{
size_t bindingCheckRound = 0;
size_t bindingIter = 0;
size_t reportIter = 0;
size_t configIter = 0;
int mgmtBindSupported = MGMT_BIND_SUPPORT_UNKNOWN;
uint8_t mgmtBindStartIndex = 0;
std::vector<BindingTracker> bindingTrackers;
std::vector<DDF_Binding> bindings;
std::vector<ReportTracker> reportTrackers;
ZCL_ReadReportConfigurationParam readReportParam;
ZCL_Result zclResult;
ZDP_Result zdpResult;
};
static ReportTracker &DEV_GetOrCreateReportTracker(Device *device, uint16_t clusterId, uint16_t attrId, uint8_t endpoint);
class DevicePrivate
{
public:
void setState(DeviceStateHandler newState, DEV_StateLevel level = StateLevel0);
void startStateTimer(int IntervalMs, DEV_StateLevel level);
void stopStateTimer(DEV_StateLevel level);
bool hasRxOnWhenIdle() const;
Device *q = nullptr; //! reference to public interface
deCONZ::ApsController *apsCtrl = nullptr; //! opaque instance pointer forwarded to external functions
/*! sub-devices are not yet referenced via pointers since these may become dangling.
This is a helper to query the actual sub-device Resource* on demand via Resource::Handle.
*/
std::array<Resource::Handle, MaxSubResources> subResourceHandles;
std::vector<Resource*> subResources;
const deCONZ::Node *node = nullptr; //! a reference to the deCONZ core node
int deviceId = DEV_INVALID_DEVICE_ID;
DeviceKey deviceKey = 0; //! for physical devices this is the MAC address
/*! The currently active state handler function(s).
Indexes >0 represent sub states of StateLevel0 running in parallel.
*/
std::array<DeviceStateHandler, StateLevelMax> state{};
std::array<QBasicTimer, StateLevelMax> timer; //! internal single shot timer one for each state level
QElapsedTimer awake; //! time to track when an end-device was last awake
BindingContext binding; //! only used by binding sub state machine
std::vector<DEV_PollItem> pollItems; //! queue of items to poll
int idleApsConfirmErrors = 0;
/*! True while a new state waits for the state enter event, which must arrive first.
This is for debug asserting that the order of events is valid - it doesn't drive logic. */
bool stateEnterLock[StateLevelMax] = {};
bool managed = false; //! a managed device doesn't rely on legacy implementation of polling etc.
ZDP_Result zdpResult; //! keep track of a running ZDP request
DA_ReadResult readResult; //! keep track of a running "read" request
uint8_t zdpNeedFetchEndpointIndex = 0xFF; //! used in combination with flags.needReadSimpleDescriptors
int maxResponseTime = RxOffWhenIdleResponseTime;
struct
{
unsigned char hasDdf : 1;
unsigned char initialRun : 1;
unsigned char needZDPMaintenanceOnce : 1;
unsigned char needReadActiveEndpoints : 1;
unsigned char needReadSimpleDescriptors : 1;
unsigned char reserved : 3;
} flags{};
};
Device *DEV_ParentDevice(Resource *r)
{
if (r && r->parentResource() && r->parentResource()->prefix() == RDevices)
{
return static_cast<Device*>(r->parentResource());
}
return nullptr;
}
//! Forward device attribute changes to core.
void DEV_ForwardNodeChange(Device *device, const QString &key, const QString &value)
{
if (device)
{
QMetaObject::invokeMethod(device->d->apsCtrl, "onRestNodeUpdated", Qt::DirectConnection,
Q_ARG(quint64, device->key()), Q_ARG(QString, key), Q_ARG(QString, value));
}
}
void DEV_EnqueueEvent(Device *device, const char *event)
{
Q_ASSERT(device);
Q_ASSERT(event);
emit device->eventNotify(Event(device->prefix(), event, 0, device->key()));
}
Resource *DEV_GetSubDevice(Device *device, const char *prefix, const QString &identifier)
{
if (!device)
{
return nullptr;
}
for (auto &sub : device->subDevices())
{
if (prefix && sub->prefix() != prefix)
{
continue;
}
if (sub->item(RAttrUniqueId)->toString() == identifier || sub->item(RAttrId)->toString() == identifier)
{
return sub;
}
}
return nullptr;
}
void DEV_InitStateHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
d->zdpResult = { };
if ((event.deviceKey() & 0x00212E0000000000LLU) == 0x00212E0000000000LLU)
{
if (!d->node)
{
d->node = DEV_GetCoreNode(device->key());
}
if (d->node && d->node->isCoordinator())
{
d->setState(DEV_DeadStateHandler);
return; // ignore coordinaor for now
}
}
}
else if (event.what() == REventStateLeave)
{
return;
}
if (event.what() == REventPoll ||
event.what() == REventAwake ||
event.what() == RConfigReachable ||
event.what() == RStateReachable ||
event.what() == REventStateTimeout ||
event.what() == RStateLastUpdated ||
d->flags.initialRun == 1)
{
d->flags.initialRun = 0;
d->binding.bindingCheckRound = 0;
// lazy reference to deCONZ::Node
if (!device->node())
{
d->node = DEV_GetCoreNode(device->key());
}
if (device->node())
{
{
const deCONZ::Address a = device->node()->address();
ResourceItem *ext = device->item(RAttrExtAddress);
if (!ext->lastSet().isValid() || ext->toNumber() != a.ext())
{
ext->setValue(a.ext());
}
ResourceItem *nwk = device->item(RAttrNwkAddress);
if (!nwk->lastSet().isValid() || nwk->toNumber() != a.nwk())
{
nwk->setValue(a.nwk());
}
}
// got a node, jump to verification
if (!device->node()->nodeDescriptor().isNull() || device->reachable())
{
d->setState(DEV_NodeDescriptorStateHandler);
}
}
else
{
DBG_Printf(DBG_DEV, "DEV Init no node found: " FMT_MAC "\n", FMT_MAC_CAST(event.deviceKey()));
if ((device->key() & 0xffffffff00000000LLU) == 0)
{
d->setState(DEV_DeadStateHandler);
return; // ignore ZGP for now
}
}
}
}
void DEV_CheckItemChanges(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
std::vector<Resource*> subDevices;
if (event.what() == REventAwake || event.what() == REventPoll)
{
subDevices = device->subDevices();
}
else
{
auto *sub = DEV_GetSubDevice(device, event.resource(), event.id());
if (sub)
{
subDevices.push_back(sub);
}
}
int apsEnqueued = 0;
for (auto *sub : subDevices)
{
if (sub && !sub->stateChanges().empty())
{
auto *item = sub->item(event.what());
for (auto &change : sub->stateChanges())
{
if (item)
{
change.verifyItemChange(item);
}
if (apsEnqueued == 0 && change.tick(d->deviceKey, sub, d->apsCtrl) == 1)
{
apsEnqueued++;
}
}
sub->cleanupStateChanges();
}
}
}
/*! #2 This state checks that a valid NodeDescriptor is available.
*/
void DEV_NodeDescriptorStateHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
if (!device->node()->nodeDescriptor().isNull())
{
DBG_Printf(DBG_DEV, "DEV ZDP node descriptor verified: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->maxResponseTime = d->hasRxOnWhenIdle() ? RxOnWhenIdleResponseTime
: RxOffWhenIdleResponseTime;
bool isSleeper = !d->hasRxOnWhenIdle();
ResourceItem *capSleeper = device->item(RCapSleeper);
if (!capSleeper->lastSet().isValid() || capSleeper->toBool() != isSleeper)
{
capSleeper->setValue(isSleeper); // can be overwritten by DDF
}
d->setState(DEV_ActiveEndpointsStateHandler);
}
else if (!device->reachable()) // can't be queried, go back to #1 init
{
d->setState(DEV_InitStateHandler);
}
else
{
d->zdpResult = ZDP_NodeDescriptorReq(d->node->address(), d->apsCtrl);
if (d->zdpResult.isEnqueued)
{
d->startStateTimer(MaxConfirmTimeout, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == REventStateLeave)
{
d->stopStateTimer(StateLevel0);
}
else if (event.what() == REventApsConfirm)
{
if (d->zdpResult.apsReqId == EventApsConfirmId(event))
{
if (EventApsConfirmStatus(event) == deCONZ::ApsSuccessStatus)
{
d->stopStateTimer(StateLevel0);
d->startStateTimer(d->maxResponseTime, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == REventNodeDescriptor) // received the node descriptor
{
d->setState(DEV_InitStateHandler); // evaluate egain from state #1 init
DEV_EnqueueEvent(device, REventAwake);
}
else if (event.what() == REventStateTimeout)
{
DBG_Printf(DBG_DEV, "DEV read ZDP node descriptor timeout: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->setState(DEV_InitStateHandler);
}
}
/*! #3 This state checks that active endpoints are known.
*/
void DEV_ActiveEndpointsStateHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
if (!device->node()->endpoints().empty() && !d->flags.needReadActiveEndpoints)
{
DBG_Printf(DBG_DEV, "DEV ZDP active endpoints verified: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->setState(DEV_SimpleDescriptorStateHandler);
}
else if (!device->reachable())
{
d->setState(DEV_InitStateHandler);
}
else
{
d->zdpResult = ZDP_ActiveEndpointsReq(d->node->address(), d->apsCtrl);
if (d->zdpResult.isEnqueued)
{
d->startStateTimer(MaxConfirmTimeout, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == REventStateLeave)
{
d->stopStateTimer(StateLevel0);
}
else if (event.what() == REventApsConfirm)
{
if (d->zdpResult.apsReqId == EventApsConfirmId(event))
{
if (EventApsConfirmStatus(event) == deCONZ::ApsSuccessStatus)
{
d->stopStateTimer(StateLevel0);
d->startStateTimer(d->maxResponseTime, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == REventActiveEndpoints)
{
d->flags.needReadActiveEndpoints = 0;
d->setState(DEV_InitStateHandler);
DEV_EnqueueEvent(device, REventAwake);
}
else if (event.what() == REventStateTimeout)
{
DBG_Printf(DBG_DEV, "DEV read ZDP active endpoints timeout: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->setState(DEV_InitStateHandler);
}
}
/*! #4 This state checks that for all active endpoints simple descriptors are known.
*/
void DEV_SimpleDescriptorStateHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
quint8 needFetchEp = 0x00;
if (d->flags.needReadSimpleDescriptors) // forced read to refresh simple descriptors
{
if (d->zdpNeedFetchEndpointIndex < device->node()->endpoints().size())
{
needFetchEp = device->node()->endpoints()[d->zdpNeedFetchEndpointIndex];
}
}
else
{
for (uint8_t ep : device->node()->endpoints())
{
bool ok = false;
for (size_t i = 0; i < device->node()->simpleDescriptors().size(); i++)
{
const deCONZ::SimpleDescriptor &sd = device->node()->simpleDescriptors()[i];
if (sd.endpoint() == ep && sd.deviceId() != 0xffff)
{
ok = true;
break;
}
}
if (!ok)
{
needFetchEp = ep;
break;
}
}
}
if (needFetchEp == 0x00)
{
DBG_Printf(DBG_DEV, "DEV ZDP simple descriptors verified: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->flags.needReadSimpleDescriptors = 0;
d->zdpNeedFetchEndpointIndex = 0xFF;
d->setState(DEV_BasicClusterStateHandler);
}
else if (!device->reachable())
{
d->setState(DEV_InitStateHandler);
}
else
{
d->zdpResult = ZDP_SimpleDescriptorReq(d->node->address(), needFetchEp, d->apsCtrl);
if (d->zdpResult.isEnqueued)
{
d->startStateTimer(MaxConfirmTimeout, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == REventStateLeave)
{
d->stopStateTimer(StateLevel0);
}
else if (event.what() == REventApsConfirm)
{
if (d->zdpResult.apsReqId == EventApsConfirmId(event))
{
if (EventApsConfirmStatus(event) == deCONZ::ApsSuccessStatus)
{
d->stopStateTimer(StateLevel0);
d->startStateTimer(d->maxResponseTime, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == REventSimpleDescriptor)
{
if (d->flags.needReadSimpleDescriptors) // forced read to refresh simple descriptors (next EP)
{
if (d->zdpNeedFetchEndpointIndex < device->node()->endpoints().size())
{
d->zdpNeedFetchEndpointIndex += 1;
}
}
d->setState(DEV_InitStateHandler);
DEV_EnqueueEvent(device, REventAwake);
}
else if (event.what() == REventStateTimeout)
{
DBG_Printf(DBG_DEV, "DEV read ZDP simple descriptor timeout: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->setState(DEV_InitStateHandler);
}
}
/*! Returns the first Simple Descriptor for a given server \p clusterId or nullptr if not found.
*/
static const deCONZ::SimpleDescriptor *DEV_GetSimpleDescriptorForServerCluster(const Device *device, deCONZ::ZclClusterId_t clusterId)
{
for (const auto &sd : device->node()->simpleDescriptors())
{
const auto cluster = std::find_if(sd.inClusters().cbegin(), sd.inClusters().cend(), [clusterId](const deCONZ::ZclCluster &cl)
{
return cl.id_t() == clusterId;
});
if (cluster != sd.inClusters().cend())
{
return &sd;
}
}
return nullptr;
}
/*! Try to fill \c ResourceItem value from \p subDevices if not already set.
*/
bool DEV_FillItemFromSubdevices(Device *device, const char *itemSuffix, const std::vector<Resource*> &subDevices)
{
auto *ditem = device->item(itemSuffix);
Q_ASSERT(ditem);
if (ditem->lastSet().isValid())
{
return true;
}
for (const auto rsub : subDevices)
{
auto *sitem = rsub->item(itemSuffix);
if (sitem && sitem->lastSet().isValid())
{
// copy from sub-device into device
if (ditem->setValue(sitem->toVariant()))
{
return true;
}
}
}
return false;
}
/*! Try to fill \c ResourceItem value from Basic cluster attributes if not already set.
*/
bool DEV_FillItemFromBasicCluster(Device *device, const char *itemSuffix, deCONZ::ZclClusterId_t clusterId, deCONZ::ZclAttributeId_t attrId)
{
ResourceItem *ditem = device->item(itemSuffix);
if (!ditem || !device->node())
{
return false;
}
if (ditem->lastSet().isValid())
{
return true;
}
for (const auto &sd : device->node()->simpleDescriptors())
{
const auto cl = std::find_if(sd.inClusters().cbegin(), sd.inClusters().cend(),
[clusterId](const auto &x) { return x.id_t() == clusterId; });
if (cl == sd.inClusters().cend()) { continue; }
const auto at = std::find_if(cl->attributes().cbegin(), cl->attributes().cend(),
[attrId](const auto &x){ return x.id_t() == attrId; });
if (at == cl->attributes().cend()) { continue; }
const QVariant v = at->toVariant();
if (!v.isNull() && ditem->setValue(v))
{
return true;
}
}
return false;
}
/*! Sends a ZCL Read Attributes request for \p clusterId and \p attrId.
This also configures generic read and parse handlers for an \p item if not already set.
*/
bool DEV_ZclRead(Device *device, ResourceItem *item, deCONZ::ZclClusterId_t clusterId, deCONZ::ZclAttributeId_t attrId)
{
Q_ASSERT(device);
Q_ASSERT(item);
DevicePrivate *d = device->d;
if (!device->reachable())
{
DBG_Printf(DBG_DEV, "DEV not reachable, skip read %s: " FMT_MAC "\n", item->descriptor().suffix, FMT_MAC_CAST(device->key()));
return false;
}
const auto *sd = DEV_GetSimpleDescriptorForServerCluster(device, clusterId);
if (!sd)
{
DBG_Printf(DBG_DEV, "DEV TODO cluster 0x%04X not found: " FMT_MAC "\n", static_cast<quint16>(clusterId), FMT_MAC_CAST(device->key()));
return false;
}
ZCL_Param param{};
param.valid = 1;
param.endpoint = sd->endpoint();
param.clusterId = static_cast<quint16>(clusterId);
param.attributes[0] = static_cast<quint16>(attrId);
param.attributeCount = 1;
const auto zclResult = ZCL_ReadAttributes(param, device->item(RAttrExtAddress)->toNumber(), device->item(RAttrNwkAddress)->toNumber(), d->apsCtrl);
d->readResult.isEnqueued = zclResult.isEnqueued;
d->readResult.apsReqId = zclResult.apsReqId;
d->readResult.sequenceNumber = zclResult.sequenceNumber;
return d->readResult.isEnqueued;
}
/*! #5 This state reads all common basic cluster attributes needed to match a DDF,
e.g. modelId, manufacturer name, application version, etc.
*/
void DEV_BasicClusterStateHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
struct _item {
const char *suffix;
deCONZ::ZclClusterId_t clusterId;
deCONZ::ZclAttributeId_t attrId;
};
const std::array<_item, 2> items = {
_item{ RAttrManufacturerName, 0x0000_clid, 0x0004_atid },
_item{ RAttrModelId, 0x0000_clid, 0x0005_atid }
};
size_t okCount = 0;
const auto &subDevices = device->subDevices();
for (const auto &it : items)
{
if (DEV_FillItemFromSubdevices(device, it.suffix, subDevices))
{
okCount++;
continue;
}
else if (DEV_FillItemFromBasicCluster(device, it.suffix, it.clusterId, it.attrId))
{
okCount++;
continue;
}
if (DEV_ZclRead(device, device->item(it.suffix), it.clusterId, it.attrId))
{
d->startStateTimer(MaxConfirmTimeout, StateLevel0);
return; // keep state and wait for REventStateTimeout or response
}
DBG_Printf(DBG_DEV, "DEV failed to read %s: " FMT_MAC "\n", it.suffix, FMT_MAC_CAST(device->key()));
break;
}
if (okCount != items.size())
{
d->setState(DEV_InitStateHandler);
}
else
{
DBG_Printf(DBG_DEV, "DEV modelId: %s, " FMT_MAC "\n", qPrintable(device->item(RAttrModelId)->toString()), FMT_MAC_CAST(device->key()));
d->setState(DEV_GetDeviceDescriptionHandler);
}
}
else if (event.what() == REventStateLeave)
{
d->stopStateTimer(StateLevel0);
}
else if (event.what() == REventApsConfirm)
{
if (d->readResult.apsReqId == EventApsConfirmId(event))
{
if (EventApsConfirmStatus(event) == deCONZ::ApsSuccessStatus)
{
d->stopStateTimer(StateLevel0);
d->startStateTimer(d->maxResponseTime, StateLevel0);
}
else
{
d->setState(DEV_InitStateHandler);
}
}
}
else if (event.what() == RAttrManufacturerName || event.what() == RAttrModelId)
{
DBG_Printf(DBG_DEV, "DEV received %s: " FMT_MAC "\n", event.what(), FMT_MAC_CAST(device->key()));
d->setState(DEV_InitStateHandler); // ok re-evaluate
DEV_EnqueueEvent(device, REventAwake);
}
else if (event.what() == REventStateTimeout)
{
DBG_Printf(DBG_DEV, "DEV read basic cluster timeout: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
d->setState(DEV_InitStateHandler);
}
}
/*! Forward device attributes to core to show it in the GUI.
*/
void DEV_PublishToCore(Device *device)
{
struct CoreItem
{
const char *suffix;
const char *mapped;
};
std::array<CoreItem, 4> coreItems = {
{
{ RAttrName, "name" },
{ RAttrModelId, "modelid" },
{ RAttrManufacturerName, "vendor" },
{ RAttrSwVersion, "version" }
}
};
const auto subDevices = device->subDevices();
if (!subDevices.empty())
{
for (const CoreItem &i : coreItems)
{
const auto *item = subDevices.front()->item(i.suffix);
if (item && !item->toString().isEmpty())
{
DEV_ForwardNodeChange(device, QLatin1String(i.mapped), item->toString());
}
}
}
}
/*! #6 This state checks if for the device a device description file (DDF) is available.
In that case the device is initialised (or updated) based on the JSON description.
The actual processing is delegated to \c DeviceDescriptions class. This is done async
so thousands of DDF files can be lazy loaded.
*/
void DEV_GetDeviceDescriptionHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
// if there is a IAS Zone Cluster add the RAttrZoneType
if (DEV_GetSimpleDescriptorForServerCluster(device, 0x0500_clid))
{
device->addItem(DataTypeUInt16, RAttrZoneType);
}
DEV_EnqueueEvent(device, REventDDFInitRequest);
}
else if (event.what() == REventDDFInitResponse)
{
DEV_PublishToCore(device);
if (event.num() == 1 || event.num() == 3)
{
d->managed = true;
d->flags.hasDdf = 1;
d->setState(DEV_IdleStateHandler);
// TODO(mpi): temporary forward this info here, gets replaced by device actor later
if (event.num() == 1)
{
DEV_ForwardNodeChange(device, QLatin1String("hasddf"), QLatin1String("1"));
}
else if (event.num() == 3)
{
DEV_ForwardNodeChange(device, QLatin1String("hasddf"), QLatin1String("2"));
}
}
else
{
d->managed = false;
d->flags.hasDdf = 0;
d->setState(DEV_DeadStateHandler);
}
}
}
void DEV_CheckReachable(Device *device)
{
DevicePrivate *d = device->d;
bool devReachable = device->reachable();
for (Resource *r : d->subResources)
{
ResourceItem *item = r->item(RConfigReachable);
if (!item)
{
item = r->item(RStateReachable);
}
if (item && ((item->toBool() != devReachable) || !item->lastSet().isValid()))
{
r->setValue(item->descriptor().suffix, devReachable);
}
}
}
/*! #7 In this state the device is operational and runs sub states
In parallel.
IdleState : Bindings | Polling | ItemChange
*/
void DEV_IdleStateHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
DEV_CheckReachable(device);
d->binding.bindingIter = 0;
d->setState(DEV_BindingHandler, STATE_LEVEL_BINDING);
d->setState(DEV_PollIdleStateHandler, STATE_LEVEL_POLL);
return;
}
else if (event.what() == REventStateLeave)
{
d->setState(nullptr, STATE_LEVEL_BINDING);
d->setState(nullptr, STATE_LEVEL_POLL);
d->stopStateTimer(STATE_LEVEL_BINDING);
d->stopStateTimer(STATE_LEVEL_POLL);
return;
}
else if (event.what() == REventApsConfirm)
{
if (EventApsConfirmStatus(event) == deCONZ::ApsSuccessStatus)
{
d->idleApsConfirmErrors = 0;
}
else
{
d->idleApsConfirmErrors++;
if (d->idleApsConfirmErrors > MaxIdleApsConfirmErrors && device->item(RStateReachable)->toBool())
{
d->idleApsConfirmErrors = 0;
DBG_Printf(DBG_DEV, "DEV Idle max APS confirm errors: " FMT_MAC "\n", FMT_MAC_CAST(device->key()));
device->item(RStateReachable)->setValue(false);
DEV_CheckReachable(device);
}
}
}
else if (event.what() != RAttrLastSeen && event.what() != REventPoll)
{
// DBG_Printf(DBG_DEV, "DEV Idle event %s/0x%016llX/%s\n", event.resource(), event.deviceKey(), event.what());
if (event.what() == RAttrSwVersion || event.what() == RAttrName)
{
DEV_PublishToCore(device);
}
}
if (!device->reachable() && !device->item(RCapSleeper)->toBool())
{
DBG_Printf(DBG_DEV, "DEV (NOT reachable) Idle event %s/" FMT_MAC "/%s\n", event.resource(), FMT_MAC_CAST(event.deviceKey()), event.what());
}
DEV_CheckItemChanges(device, event);
// process parallel states
for (int i = StateLevel1; i < StateLevelMax; i++)
{
device->handleEvent(event, DEV_StateLevel(i));
}
}
/*! Bindings sub state machien is described in:
https://github.com/dresden-elektronik/deconz-rest-plugin-v2/wiki/Device-Class#bindings-sub-state-machine
*/
void DEV_BindingHandler(Device *device, const Event &event)
{
DevicePrivate *d = device->d;
if (event.what() == REventStateEnter)
{
DBG_Printf(DBG_DEV, "DEV Binding enter %s/" FMT_MAC "\n", event.resource(), FMT_MAC_CAST(event.deviceKey()));
}
else if (event.what() == REventPoll || event.what() == REventAwake || event.what() == REventBindingTick)
{
if (DA_ApsUnconfirmedRequests() > 4)
{
// wait
}
else
{
d->binding.bindingIter = 0;
if (d->binding.mgmtBindSupported == MGMT_BIND_NOT_SUPPORTED)
{
d->setState(DEV_BindingTableVerifyHandler, STATE_LEVEL_BINDING);
}
else
{
d->setState(DEV_BindingTableReadHandler, STATE_LEVEL_BINDING);
}
}
}
else if (event.what() == REventBindingTable)
{
if (event.num() == deCONZ::ZdpSuccess)
{
d->binding.mgmtBindSupported = MGMT_BIND_SUPPORTED;