-
Notifications
You must be signed in to change notification settings - Fork 13
/
std_otau_plugin.cpp
2166 lines (1803 loc) · 61.4 KB
/
std_otau_plugin.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 <QDebug>
#include <QDir>
#include <QSettings>
#include <QtPlugin>
#include <QTimer>
#include <stdint.h>
#include "std_otau_plugin.h"
#include "std_otau_widget.h"
#include "otau_file.h"
#include "otau_file_loader.h"
#include "otau_node.h"
#include "otau_model.h"
#ifdef USE_ACTOR_MODEL
#include <actor/plugin.h>
#include <actor/cxx_helper.h>
#endif
#define VENDOR_BUSCH_JAEGER 0x112E
#define VENDOR_DDEL 0x1135
#define IMG_TYPE_FLS_PP3_H3 0x0000
#define IMG_TYPE_FLS_NB 0x0002
#define IMG_TYPE_FLS_A2 0x0004
#define IMG_TYPE_FLS_H3 0x0008
#define MAX_RADIUS 0
#define MAX_ASDU_SIZE 82
/* Source routing adds additional bytes to the NWK header, reducing the ASDU size.
U8 relay count
U8 relay index
U16 relay 1
U16 relay 2
...
U16 relay n
By default, maximum hops is set to 5.
Ideally, the core would report whether source routing is enabled, and the value of max hops.
For now, we count the number of consecutive NO_ACK errors to try and detect source routing.
*/
//#define SOURCE_ROUTING_MAX_HOPS 7
//#define SOURCE_ROUTING_SIZE (1 + 1 + (2 * SOURCE_ROUTING_MAX_HOPS))
// some older devices support max. 40 bytes data size
// use this also als fallback due source routing overhead
#define MAX_SAFE_ASDU_SIZE (40 + ZCL_HEADER_SIZE + IMAGE_BLOCK_RSP_HEADER_SIZE)
#define NO_ACK_THRESHOLD 3
// #define MAX_ASDU_SIZE1 45
// #define MAX_ASDU_SIZE2 45
// #define MAX_ASDU_SIZE3 82
/*
U8 status
U16 manufacturerCode;
U16 imageType;
U32 fileVersion;
U32 offset;
U8 dataSize
*/
#define IMAGE_BLOCK_RSP_HEADER_SIZE (1 + 2 + 2 + 4 + 4 + 1) // 14
#define ZCL_HEADER_SIZE (1 + 1 + 1) // frame control + seq + commandId
// for widest device support use 50 bytes max
#define MAX_DATA_SIZE qMin(50, (m_maxAsduDataSize - (ZCL_HEADER_SIZE + IMAGE_BLOCK_RSP_HEADER_SIZE)))
#define MIN_RESPONSE_SPACING 20
#define MAX_RESPONSE_SPACING 500
#define DEFAULT_UPGRADE_TIME 5
#define CLEANUP_TIMER_DELAY (3 * 60 * 1000)
#define CLEANUP_DELAY (4 * 60 * 60 * 1000)
#define IMAGE_PAGE_TIMER_DELAY 10
#define ACTIVITY_TIMER_DELAY 3000
#define MAX_ACTIVITY 120 // hits 0 after 5 seconds
#define MAX_IMG_PAGE_REQ_RETRY 5
#define MAX_IMG_BLOCK_RSP_RETRY 10
#define WAIT_NEXT_REQUEST_TIMEOUT 60000
#define INVALID_APS_REQ_ID (0xff + 1) // request ids are 8-bit
#define FAST_PAGE_SPACEING 25
#define MIN_PAGE_SPACEING 20
#define MAX_PAGE_SPACEING 3000
#define OTA_TIME_INFINITE 0xFFFFFFFFUL
#define DONT_CARE_FILE_VERSION 0xFFFFFFFFUL
/* .ota-cache file
4096 byte pages
Entry {
U16 marker // 0 = empty
U16 page_count
U16 mfcode
U16 image_type
U32 crc32
U8 filename_length
U8 filename[127] // '\0' right padded
U8 sha256[32]
}
*/
const quint64 macPrefixMask = 0xffffff0000000000ULL;
// const quint64 develcoMacPrefix = 0x0015bc0000000000ULL;
// const quint64 philipsMacPrefix = 0x0017880000000000ULL;
// const quint64 ubisysMacPrefix = 0x001fee0000000000ULL;
const quint64 osramMacPrefix = 0x8418260000000000ULL;
// const quint64 bjeMacPrefix = 0xd85def0000000000ULL;
const deCONZ::SimpleDescriptor *getSimpleDescriptor(const deCONZ::Node *node, quint8 ep)
{
if (!node)
{
return nullptr;
}
const auto i = std::find_if(node->simpleDescriptors().cbegin(), node->simpleDescriptors().cend(),
[ep](const deCONZ::SimpleDescriptor &sd){ return sd.endpoint() == ep; });
if (i != node->simpleDescriptors().cend())
{
return &*i;
}
return nullptr;
}
#ifdef USE_ACTOR_MODEL
enum CommonMessageIds
{
M_ID_LIST_DIR_REQ = AM_MESSAGE_ID_COMMON_REQUEST(1),
M_ID_LIST_DIR_RSP = AM_MESSAGE_ID_COMMON_RESPONSE(1),
M_ID_READ_ENTRY_REQ = AM_MESSAGE_ID_COMMON_REQUEST(2),
M_ID_READ_ENTRY_RSP = AM_MESSAGE_ID_COMMON_RESPONSE(2)
};
#define AM_ACTOR_ID_OTA 9000
#define AM_ACTOR_ID_CORE_APS 2005
#define OTA_M_ID_QUERY_NEXT_IMAGE_NOTIFY AM_MESSAGE_ID_SPECIFIC_NOTIFY(0x0001)
static struct am_actor am_actor_ota0;
struct am_api_functions *am = nullptr;
static int OTA_ReadEntryRequest(struct am_message *msg)
{
struct am_message *m;
uint16_t tag;
am_string url;
uint32_t mode = 0;
uint64_t mtime = 0;
tag = am->msg_get_u16(msg);
url = am->msg_get_string(msg);
if (msg->status != AM_MSG_STATUS_OK)
return AM_CB_STATUS_INVALID;
m = am->msg_alloc();
if (!m)
return AM_CB_STATUS_MESSAGE_ALLOC_FAILED;
am->msg_put_u16(m, tag);
am->msg_put_u8(m, AM_RESPONSE_STATUS_OK);
am->msg_put_string(m, url.data, url.size);
if (url == ".actor/name")
{
am->msg_put_cstring(m, "str");
am->msg_put_u32(m, mode);
am->msg_put_u64(m, mtime);
am->msg_put_cstring(m, "ota");
}
else
{
m->pos = 0;
}
if (m->pos == 0)
{
am->msg_put_u16(m, tag);
am->msg_put_u8(m, AM_RESPONSE_STATUS_NOT_FOUND);
}
m->src = msg->dst;
m->dst = msg->src;
m->id = M_ID_READ_ENTRY_RSP;
am->send_message(m);
return AM_CB_STATUS_OK;
}
static int OTA0_MessageCallback(struct am_message *msg)
{
if (msg->id == M_ID_READ_ENTRY_REQ)
return OTA_ReadEntryRequest(msg);
return AM_CB_STATUS_UNSUPPORTED;
}
/* actor model init entry point, called by actor model service in core */
extern "C"
#ifdef _WIN32
__declspec(dllexport)
#endif
int am_plugin_init(struct am_api_functions *api)
{
struct am_message *m;
am = api;
AM_INIT_ACTOR(&am_actor_ota0, AM_ACTOR_ID_OTA, OTA0_MessageCallback);
am->register_actor(&am_actor_ota0);
am->subscribe(AM_ACTOR_ID_CORE_APS, AM_ACTOR_ID_OTA);
return 1;
}
#endif // USE_ACTOR_MODEL
/*! The constructor.
*/
StdOtauPlugin::StdOtauPlugin(QObject *parent) :
QObject(parent)
{
m_state = StateEnabled;
m_w = nullptr;
m_srcEndpoint = 0x01; // TODO: ask from controller
m_model = new OtauModel(this);
m_imagePageTimer = new QTimer(this);
m_maxAsduDataSize = MAX_ASDU_SIZE;
m_nNoAckErrors = 0;
m_imagePageTimer->setSingleShot(true);
m_imagePageTimer->setInterval(IMAGE_PAGE_TIMER_DELAY);
connect(m_imagePageTimer, SIGNAL(timeout()),
this, SLOT(imagePageTimerFired()));
m_cleanupTimer = new QTimer(this);
m_cleanupTimer->setSingleShot(true);
m_cleanupTimer->setInterval(CLEANUP_TIMER_DELAY);
connect(m_cleanupTimer, SIGNAL(timeout()),
this, SLOT(cleanupTimerFired()));
m_activityTimer = new QTimer(this);
m_activityTimer->setSingleShot(false);
connect(m_activityTimer, SIGNAL(timeout()),
this, SLOT(activityTimerFired()));
//QString defaultImgPath = deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + "/otau";
QString defaultImgPath = deCONZ::getStorageLocation(deCONZ::HomeLocation) + "/otau";
m_imgPath = deCONZ::appArgumentString("--otau-img-path", defaultImgPath);
QDir otauDir(m_imgPath);
if (otauDir.exists())
{
DBG_Printf(DBG_OTA, "OTAU: image path: %s\n", qPrintable(m_imgPath));
}
else
{
DBG_Printf(DBG_ERROR, "OTAU: image path does not exist: %s\n", qPrintable(m_imgPath));
}
deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance();
connect(apsCtrl, SIGNAL(apsdeDataConfirm(deCONZ::ApsDataConfirm)),
this, SLOT(apsdeDataConfirm(deCONZ::ApsDataConfirm)));
connect(apsCtrl, SIGNAL(apsdeDataIndication(deCONZ::ApsDataIndication)),
this, SLOT(apsdeDataIndication(deCONZ::ApsDataIndication)));
connect(apsCtrl, SIGNAL(nodeEvent(deCONZ::NodeEvent)),
this, SLOT(nodeEvent(deCONZ::NodeEvent)));
QSettings config(deCONZ::getStorageLocation(deCONZ::ConfigLocation), QSettings::IniFormat);
// fast page spacing
bool ok = false;
m_fastPageSpaceing = FAST_PAGE_SPACEING;
if (config.contains("otau/fast-page-spacing"))
{
int sp = config.value("otau/fast-page-spacing", FAST_PAGE_SPACEING).toInt(&ok);
if (ok && sp >= MIN_PAGE_SPACEING && sp < MAX_PAGE_SPACEING)
{
m_fastPageSpaceing = sp;
}
}
if (!ok)
{
config.setValue("otau/fast-page-spacing", m_fastPageSpaceing);
}
checkFileLinks();
}
/*! APSDE-DATA.indication callback.
\param ind - the indication primitive
\note Will be called from the main application for each incoming indication.
Any filtering for nodes, profiles, clusters must be handled by this plugin.
*/
void StdOtauPlugin::apsdeDataIndication(const deCONZ::ApsDataIndication &ind)
{
deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance();
if (!apsCtrl)
{
return;
}
if (apsCtrl->getParameter(deCONZ::ParamOtauActive) == 0)
{
setState(StateDisabled);
}
else if (state() == StateDisabled)
{
setState(StateEnabled);
}
if (ind.profileId() == ZDP_PROFILE_ID && ind.clusterId() == ZDP_MATCH_DESCRIPTOR_CLID)
{
matchDescriptorRequest(ind);
}
if (ind.clusterId() != OTAU_CLUSTER_ID)
{
return;
}
deCONZ::ZclFrame zclFrame;
QDataStream stream(ind.asdu());
stream.setByteOrder(QDataStream::LittleEndian);
zclFrame.readFromStream(stream);
// filter
if (zclFrame.isClusterCommand())
{
switch (zclFrame.commandId())
{
case OTAU_QUERY_NEXT_IMAGE_REQUEST_CMD_ID:
case OTAU_IMAGE_BLOCK_REQUEST_CMD_ID:
case OTAU_IMAGE_PAGE_REQUEST_CMD_ID:
case OTAU_UPGRADE_END_REQUEST_CMD_ID:
m_cleanupTimer->stop();
m_cleanupTimer->start();
break;
default:
return;
}
}
else
{
if (zclFrame.commandId() == deCONZ::ZclDefaultResponseId)
{
switch (zclFrame.defaultResponseCommandId())
{
case OTAU_QUERY_NEXT_IMAGE_REQUEST_CMD_ID:
case OTAU_QUERY_NEXT_IMAGE_RESPONSE_CMD_ID:
case OTAU_IMAGE_BLOCK_REQUEST_CMD_ID:
case OTAU_IMAGE_BLOCK_RESPONSE_CMD_ID:
case OTAU_IMAGE_PAGE_REQUEST_CMD_ID:
case OTAU_UPGRADE_END_REQUEST_CMD_ID:
case OTAU_UPGRADE_END_RESPONSE_CMD_ID:
DBG_Printf(DBG_OTA, "OTAU: 0x%016llX default rsp cmd: 0x%02X, status 0x%02X, seq: %u\n", ind.srcAddress().ext(), zclFrame.defaultResponseCommandId(), (uint8_t)zclFrame.defaultResponseStatus(), zclFrame.sequenceNumber());
break;
default:
break;
}
return;
}
}
bool create = true;
OtauNode *node = m_model->getNode(ind.srcAddress(), create);
if (!node)
{
return;
}
node->lastActivity.invalidate();
node->lastActivity.start();
if (!zclFrame.isDefaultResponse())
{
node->setLastZclCommand(zclFrame.commandId());
}
// filter
if (zclFrame.isClusterCommand())
{
switch (zclFrame.commandId())
{
case OTAU_QUERY_NEXT_IMAGE_REQUEST_CMD_ID:
queryNextImageRequest(ind, zclFrame);
break;
case OTAU_IMAGE_BLOCK_REQUEST_CMD_ID:
imageBlockRequest(ind, zclFrame);
break;
case OTAU_IMAGE_PAGE_REQUEST_CMD_ID:
imagePageRequest(ind, zclFrame);
break;
case OTAU_UPGRADE_END_REQUEST_CMD_ID:
upgradeEndRequest(ind, zclFrame);
break;
default:
break;
}
}
m_model->nodeDataUpdate(node);
}
/*! APSDE-DATA.confirm callback.
\param conf - the confirm primitive
\note Will be called from the main application for each incoming confirmation,
even if the APSDE-DATA.request was not issued by this plugin.
*/
void StdOtauPlugin::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf)
{
if (!conf.dstAddress().isNwkUnicast())
return;
OtauNode *node = m_model->getNode(conf.dstAddress());
if (node)
{
if (node->state() == OtauNode::NodeAbort)
{
return;
}
if (node->apsRequestId == INVALID_APS_REQ_ID)
{ }
else if (node->apsRequestId == conf.id())
{
node->apsRequestId = INVALID_APS_REQ_ID;
if (conf.status() != deCONZ::ApsSuccessStatus)
{
DBG_Printf(DBG_OTA, "OTAU: aps conf failed status 0x%02X\n", conf.status());
// FIXME hack to detect source routing
// note that no ack doesn't always refer to source routing but this provides a safe fallback
if (conf.status() == deCONZ::ApsNoAckStatus || conf.status() == 0xE5 /* ??? */)
{
if (++m_nNoAckErrors > NO_ACK_THRESHOLD ||
(node->zclCommandId == OTAU_IMAGE_BLOCK_RESPONSE_CMD_ID &&
node->imgBlockReq.offset == 0)
)
{
if (m_maxAsduDataSize > MAX_SAFE_ASDU_SIZE)
{
m_maxAsduDataSize = MAX_SAFE_ASDU_SIZE;
DBG_Printf(DBG_OTA, "OTAU: reducing max data size to %d\n", MAX_DATA_SIZE);
}
}
}
else
{
m_nNoAckErrors = 0;
}
// End FIXME
}
else
{
node->refreshTimeout();
if (node->zclCommandId == OTAU_IMAGE_BLOCK_RESPONSE_CMD_ID)
{
node->imgBlockReq.pageBytesDone += node->imgBlockReq.maxDataSize;
node->imgBlockReq.offset += node->imgBlockReq.maxDataSize;
node->reqSequenceNumber++;
if (node->state() == OtauNode::NodeWaitPageSpacing)
{
imagePageResponse(node);
}
}
}
if (node->zclCommandId == OTAU_UPGRADE_END_RESPONSE_CMD_ID)
{
if (conf.status() == deCONZ::ApsSuccessStatus)
{
node->setHasData(false);
}
}
}
}
}
/*! Handler for node events.
\param event - the event which occured
*/
void StdOtauPlugin::nodeEvent(const deCONZ::NodeEvent &event)
{
if (event.event() != deCONZ::NodeEvent::NodeDeselected && !event.node())
{
return;
}
if (event.event() == deCONZ::NodeEvent::UpdatedSimpleDescriptor)
{
checkIfNewOtauNode(event.node(), event.endpoint());
}
else if (event.event() == deCONZ::NodeEvent::NodeSelected)
{
nodeSelected(event.node());
}
else if (event.event() == deCONZ::NodeEvent::NodeDeselected)
{
m_w->clearNode();
}
else if (event.event() == deCONZ::NodeEvent::NodeRemoved)
{
// TODO: Remove node from model and tableview
}
}
void StdOtauPlugin::nodeSelected(const deCONZ::Node *node)
{
if (!m_model || m_model->nodes().empty())
{
return;
}
OtauNode *otauNode = m_model->getNode(node->address());
if (otauNode != nullptr)
{
m_w->displayNode(otauNode, m_model->index(otauNode->row, 0));
}
else
{
m_w->clearNode();
}
}
/*! Checks if a new otau image for the node is available in the otau folder.
Otau images must be in the <otau> directory and must have a proper formatted filename.
All numbers are hexaecimal and in capital letters.
filename: <manufacturer code>-<imagetype>-<fileversion>-someArbitraryText.zigbee
example: 113D-AB12-1F010400-FLS-RGB.zigbee
\param node - the node for which the check will be done
\param path - the path to look for .zigbee files
*/
bool StdOtauPlugin::checkForUpdateImageImage(OtauNode *node, const QString &path)
{
deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance();
if (!apsCtrl)
{
return false;
}
if (apsCtrl->getParameter(deCONZ::ParamOtauActive) == 0)
{
return false;
}
bool ok;
uint32_t cmpFileVersion = node->softwareVersion();
uint32_t fileVersion;
uint16_t imageType;
uint16_t manufacturerId;
QString updateFile = "";
QDir dir(path);
if (!dir.exists())
{
DBG_Printf(DBG_OTA, "OTAU: image path does not exist: %s\n", qPrintable(path));
return false;
}
QStringList ls = dir.entryList();
auto i = ls.begin();
auto end = ls.end();
for (; i != end; ++i)
{
if (!i->endsWith(".zigbee"))
{
continue;
}
QString plain = *i;
plain.replace(".zigbee", "");
QStringList args = plain.split('-');
if (args.size() >= 3)
{
manufacturerId = args[0].toUShort(&ok, 16);
if (!ok || manufacturerId != node->manufacturerId)
{
continue;
}
imageType = args[1].toUShort(&ok, 16);
if (!ok)
{
continue;
}
if (imageType == node->imageType())
{
fileVersion = args[2].toUInt(&ok, 16);
if (!ok)
{
continue;
}
if (fileVersion > cmpFileVersion)
{
updateFile = *i;
cmpFileVersion = fileVersion;
DBG_Printf(DBG_OTA, "OTAU: Match otau version 0x%08X image type 0x%04X\n", fileVersion, imageType);
}
}
}
}
if (!updateFile.isEmpty())
{
updateFile.prepend(path + "/");
OtauFileLoader ld;
if (ld.readFile(updateFile, node->file))
{
node->setHasData(true);
DBG_Printf(DBG_OTA, "OTAU: found update file %s\n", qPrintable(updateFile));
}
else
{
node->setHasData(false);
DBG_Printf(DBG_OTA, "OTAU: found invalid update file %s\n", qPrintable(updateFile));
}
}
return false;
}
/*! Invalidates the upgrade end request.
*/
void StdOtauPlugin::invalidateUpdateEndRequest(OtauNode *node)
{
if (node)
{
if ((node->upgradeEndReq.fileVersion != 0) || (node->upgradeEndReq.manufacturerCode != 0))
{
DBG_Printf(DBG_OTA, "OTAU: invalid update end request for node " FMT_MAC "\n", FMT_MAC_CAST(node->address().ext()));
}
node->upgradeEndReq.status = 0;
node->upgradeEndReq.manufacturerCode = 0;
node->upgradeEndReq.fileVersion = 0;
node->upgradeEndReq.imageType = 0;
}
}
/*! Handler to automatically send image page responses.
*/
void StdOtauPlugin::imagePageTimerFired()
{
if (!m_model || m_model->nodes().empty())
{
return;
}
deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance();
if (!apsCtrl)
{
return;
}
if (apsCtrl->getParameter(deCONZ::ParamOtauActive) == 0)
{
return;
}
bool refire = false;
for (OtauNode *node : m_model->nodes())
{
if (!node)
continue;
if (node->state() == OtauNode::NodeWaitPageSpacing)
{
refire = true;
if (!imagePageResponse(node))
{
if (node->imgBlockResponseRetry >= MAX_IMG_BLOCK_RSP_RETRY)
{
// giveup
node->setState(OtauNode::NodeIdle);
}
}
}
else if (node->state() == OtauNode::NodeWaitNextRequest)
{
refire = true;
if (node->lastActivity.hasExpired(WAIT_NEXT_REQUEST_TIMEOUT))
{
node->imgPageRequestRetry++;
if (node->imgPageRequestRetry >= MAX_IMG_PAGE_REQ_RETRY)
{
// giveup
node->setState(OtauNode::NodeIdle);
}
else
{
DBG_Printf(DBG_OTA, "OTAU: wait request timeout (retry %d)\n", node->imgPageRequestRetry);
node->apsRequestId = INVALID_APS_REQ_ID; // don't wait for prior requests
if (node->imgPageRequestRetry < 3)
{
unicastImageNotify(node->address());
}
}
}
}
}
if (refire && !m_imagePageTimer->isActive())
{
m_imagePageTimer->start(IMAGE_PAGE_TIMER_DELAY);
}
}
/*! Handler to cleanup timed out nodes.
*/
void StdOtauPlugin::cleanupTimerFired()
{
if (!m_model)
{
return;
}
int activeNodes = 0;
std::vector<OtauNode*>::iterator i = m_model->nodes().begin();
std::vector<OtauNode*>::iterator end = m_model->nodes().end();
for (; i != end; ++i)
{
OtauNode *node = *i;
if (node->hasData())
{
if (node->lastActivity.hasExpired(CLEANUP_DELAY))
{
node->file.subElements.clear();
node->setHasData(false);
DBG_Printf(DBG_OTA, "OTAU: cleanup node\n");
}
else
{
activeNodes++;
}
}
}
if (activeNodes)
{
m_cleanupTimer->start();
}
}
void StdOtauPlugin::activityTimerFired()
{
const auto now = deCONZ::steadyTimeRef();
auto i = std::find_if(m_otauTracker.begin(), m_otauTracker.end(), [&](const OtauTracker &t)
{
return deCONZ::TimeSeconds{10} < (now - t.lastActivity);
});
if (i != m_otauTracker.end())
{
m_otauTracker.erase(i);
}
if (m_otauTracker.empty())
{
m_activityTimer->stop();
}
}
void StdOtauPlugin::markOtauActivity(const deCONZ::Address &address)
{
if (!address.hasExt())
{
return;
}
auto i = std::find_if(m_otauTracker.begin(), m_otauTracker.end(), [&](const OtauTracker &t)
{
return t.extAddr == address.ext();
});
if (i != m_otauTracker.end())
{
i->lastActivity = deCONZ::steadyTimeRef();
}
else if (m_otauTracker.size() < OTAU_MAX_ACTIVE)
{
OtauTracker t;
t.extAddr = address.ext();
t.lastActivity = deCONZ::steadyTimeRef();
m_otauTracker.push_back(t);
}
if (!m_activityTimer->isActive())
{
m_activityTimer->start(ACTIVITY_TIMER_DELAY);
}
}
void StdOtauPlugin::checkFileLinks()
{
QStringList paths;
paths.append(m_imgPath);
//paths.append(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + "/otau");
for (const QString &path : paths)
{
QDir dir(path);
if (!dir.exists())
{
continue;
}
const QStringList ls = dir.entryList();
for (const QString &n : ls)
{
QFile file(path + "/" + n);
if (!file.open(QFile::ReadOnly))
continue;
QByteArray arr = file.readAll();
if (arr.isEmpty())
continue;
OtauFile of;
of.path = n;
if (!of.fromArray(arr))
continue;
const QString fname = QString("%1-%2-%3").arg(of.manufacturerCode, 4, 16, QLatin1Char('0'))
.arg(of.imageType, 4, 16, QLatin1Char('0'))
.arg(of.fileVersion, 8, 16, QLatin1Char('0'))
.toUpper();
bool ok= false;
for (const QString &n2 : ls)
{
if (n2.startsWith(fname))
{
ok = true;
break;
}
}
if (ok)
continue;
DBG_Printf(DBG_INFO, "OTAU: create %s.zigbee\n", qPrintable(fname));
file.copy(path + "/" + fname + ".zigbee");
}
}
}
/*! Sends a image notify request.
\param notf - the request parameters
\return true on success false otherwise
*/
bool StdOtauPlugin::imageNotify(ImageNotifyReq *notf)
{
if (m_state == StateEnabled)
{
deCONZ::ApsDataRequest req;
deCONZ::ZclFrame zclFrame;
OtauNode *node = m_model->getNode(notf->addr);
req.setDstAddressMode(notf->addrMode);
req.dstAddress() = notf->addr;
req.setDstEndpoint(notf->dstEndpoint);
req.setSrcEndpoint(m_srcEndpoint);
req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
if (node)
{
req.setProfileId(node->profileId);
DBG_Printf(DBG_OTA, "OTAU: send img notify to " FMT_MAC "\n", FMT_MAC_CAST(node->address().ext()));
}
else
{
req.setProfileId(0x0104);
}
req.setClusterId(OTAU_CLUSTER_ID);
req.setRadius(notf->radius);
zclFrame.setSequenceNumber(m_zclSeq++);
zclFrame.setCommandId(OTAU_IMAGE_NOTIFY_CMD_ID);
uint8_t frameControl = deCONZ::ZclFCClusterCommand |
deCONZ::ZclFCDirectionServerToClient;
if (notf->addr.isNwkBroadcast())
{
frameControl |= deCONZ::ZclFCDisableDefaultResponse;
}
zclFrame.setFrameControl(frameControl);
{ // ZCL payload
QDataStream stream(&zclFrame.payload(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
stream << static_cast<quint8>(0x00); // query jitter
stream << static_cast<quint8>(100); // query jitter value
}
{ // ZCL frame
QDataStream stream(&req.asdu(), QIODevice::WriteOnly);
stream.setByteOrder(QDataStream::LittleEndian);
zclFrame.writeToStream(stream);
}
if (deCONZ::ApsController::instance()->apsdeDataRequest(req) == deCONZ::Success)
{
return true;
}
}
return false;
}
/*! Broadcasts a image notify request.
*/
bool StdOtauPlugin::broadcastImageNotify()
{
ImageNotifyReq notf;
notf.radius = 0;
notf.addr.setNwk(deCONZ::BroadcastRxOnWhenIdle);
notf.addrMode = deCONZ::ApsNwkAddress;
notf.dstEndpoint = 0xFF; // broadcast endpoint
return imageNotify(¬f);
}
/*! Sends a image notify request per unicast.
\param addr - the destination address
\return true on success false otherwise
*/
bool StdOtauPlugin::unicastImageNotify(const deCONZ::Address &addr)
{
if (addr.hasExt())
{
ImageNotifyReq notf;
OtauNode *node = m_model->getNode(addr);
if (!node)
{
return false;
}
notf.radius = 0;
notf.addr = addr;
notf.addrMode = deCONZ::ApsExtAddress;
notf.dstEndpoint = node->endpoint;
// blacklist some faulty versions tue image notify bug in BitCloud 3.2, 3.3
if (node->manufacturerId == VENDOR_DDEL)
{
node->endpointNotify = 0x0A;
notf.dstEndpoint = node->endpointNotify;