forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
de_web_plugin.cpp
12776 lines (11146 loc) · 436 KB
/
de_web_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
/*
* Copyright (c) 2017-2018 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 <QCoreApplication>
#include <QDebug>
#include <QDesktopServices>
#include <QtPlugin>
#include <QtCore/qmath.h>
#include <QNetworkAccessManager>
#include <QPushButton>
#include <QTextCodec>
#include <QTime>
#include <QTimer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QUrl>
#include <QCryptographicHash>
#include <QFile>
#include <QProcess>
#include <queue>
#include <cmath>
#ifdef ARCH_ARM
#include <unistd.h>
#include <sys/reboot.h>
#include <errno.h>
#endif
#include "colorspace.h"
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "de_web_widget.h"
#include "gateway_scanner.h"
#include "json.h"
#include "poll_manager.h"
const char *HttpStatusOk = "200 OK"; // OK
const char *HttpStatusAccepted = "202 Accepted"; // Accepted but not complete
const char *HttpStatusNotModified = "304 Not Modified"; // For ETag / If-None-Match
const char *HttpStatusBadRequest = "400 Bad Request"; // Malformed request
const char *HttpStatusUnauthorized = "401 Unauthorized"; // Unauthorized
const char *HttpStatusForbidden = "403 Forbidden"; // Understand request but no permission
const char *HttpStatusNotFound = "404 Not Found"; // Requested uri not found
const char *HttpStatusServiceUnavailable = "503 Service Unavailable";
const char *HttpStatusNotImplemented = "501 Not Implemented";
const char *HttpContentHtml = "text/html; charset=utf-8";
const char *HttpContentCss = "text/css";
const char *HttpContentJson = "application/json; charset=utf-8";
const char *HttpContentJS = "text/javascript";
const char *HttpContentPNG = "image/png";
const char *HttpContentJPG = "image/jpg";
const char *HttpContentSVG = "image/svg+xml";
static int checkZclAttributesDelay = 750;
//static int ReadAttributesLongDelay = 5000;
//static int ReadAttributesLongerDelay = 60000;
static uint MaxGroupTasks = 4;
const quint64 macPrefixMask = 0xffffff0000000000ULL;
const quint64 bjeMacPrefix = 0xd85def0000000000ULL;
const quint64 emberMacPrefix = 0x000d6f0000000000ULL;
const quint64 tiMacPrefix = 0x00124b0000000000ULL;
const quint64 deMacPrefix = 0x00212e0000000000ULL;
const quint64 ikeaMacPrefix = 0x000b570000000000ULL;
const quint64 instaMacPrefix = 0x000f170000000000ULL;
const quint64 jennicMacPrefix = 0x00158d0000000000ULL;
const quint64 philipsMacPrefix = 0x0017880000000000ULL;
const quint64 osramMacPrefix = 0x8418260000000000ULL;
const quint64 ubisysMacPrefix = 0x001fee0000000000ULL;
const quint64 netvoxMacPrefix = 0x00137a0000000000ULL;
const quint64 heimanMacPrefix = 0x0050430000000000ULL;
const quint64 lutronMacPrefix = 0xffff000000000000ULL;
struct SupportedDevice {
quint16 vendorId;
const char *modelId;
quint64 mac;
};
static const SupportedDevice supportedDevices[] = {
{ VENDOR_BUSCH_JAEGER, "RB01", bjeMacPrefix },
{ VENDOR_BUSCH_JAEGER, "RM01", bjeMacPrefix },
{ VENDOR_CENTRALITE, "Motion Sensor-A", emberMacPrefix },
{ VENDOR_CENTRALITE, "3325-S", emberMacPrefix },
{ VENDOR_CENTRALITE, "3321-S", emberMacPrefix },
{ VENDOR_NONE, "LM_", tiMacPrefix },
{ VENDOR_NONE, "LMHT_", tiMacPrefix },
{ VENDOR_NONE, "IR_", tiMacPrefix },
{ VENDOR_NONE, "DC_", tiMacPrefix },
{ VENDOR_NONE, "OJB-IR715-Z", tiMacPrefix },
{ VENDOR_NONE, "902010/21A", tiMacPrefix }, // Bitron: door/window sensor
{ VENDOR_NONE, "902010/25", tiMacPrefix }, // Bitron: smart plug
{ VENDOR_DDEL, "Lighting Switch", deMacPrefix },
{ VENDOR_DDEL, "Scene Switch", deMacPrefix },
{ VENDOR_DDEL, "FLS-NB1", deMacPrefix },
{ VENDOR_DDEL, "FLS-NB2", deMacPrefix },
{ VENDOR_IKEA, "TRADFRI remote control", ikeaMacPrefix },
{ VENDOR_IKEA, "TRADFRI motion sensor", ikeaMacPrefix },
{ VENDOR_IKEA, "TRADFRI wireless dimmer", ikeaMacPrefix },
{ VENDOR_INSTA, "Remote", instaMacPrefix },
{ VENDOR_INSTA, "HS_4f_GJ_1", instaMacPrefix },
{ VENDOR_INSTA, "WS_4f_J_1", instaMacPrefix },
{ VENDOR_INSTA, "WS_3f_G_1", instaMacPrefix },
{ VENDOR_NYCE, "3011", emberMacPrefix }, // door/window sensor
{ VENDOR_PHILIPS, "RWL020", philipsMacPrefix }, // Hue dimmer switch
{ VENDOR_PHILIPS, "RWL021", philipsMacPrefix }, // Hue dimmer switch
{ VENDOR_PHILIPS, "SML001", philipsMacPrefix }, // Hue motion sensor
{ VENDOR_JENNIC, "lumi.sensor_ht", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.weather", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_magnet", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_motion", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_switch", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_cube", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_86sw1", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_86sw2", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.ctrl_neutral1", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.ctrl_neutral2", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_wleak", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.sensor_smoke", jennicMacPrefix },
{ VENDOR_JENNIC, "lumi.plug", jennicMacPrefix }, // TODO: check whether VENDOR_JENNIC is actually used
{ VENDOR_115F, "lumi.plug", jennicMacPrefix }, // Xiaomi smart plug
{ VENDOR_UBISYS, "D1", ubisysMacPrefix },
{ VENDOR_UBISYS, "C4", ubisysMacPrefix },
{ VENDOR_NONE, "Z716A", netvoxMacPrefix },
{ VENDOR_OSRAM_STACK, "Plug", osramMacPrefix }, // OSRAM plug
{ VENDOR_OSRAM_STACK, "CO_", heimanMacPrefix }, // Heiman CO sensor
{ VENDOR_OSRAM_STACK, "DOOR_", heimanMacPrefix }, // Heiman door/window sensor
{ VENDOR_OSRAM_STACK, "PIR_", heimanMacPrefix }, // Heiman motion sensor
{ VENDOR_OSRAM_STACK, "GAS_", heimanMacPrefix }, // Heiman gas sensor
{ VENDOR_OSRAM_STACK, "TH-H_", heimanMacPrefix }, // Heiman temperature/humidity sensor
{ VENDOR_OSRAM_STACK, "TH-T_", heimanMacPrefix }, // Heiman temperature/humidity sensor
{ VENDOR_OSRAM_STACK, "SMOK_", heimanMacPrefix }, // Heiman fire sensor
{ VENDOR_OSRAM_STACK, "WATER_", heimanMacPrefix }, // Heiman water sensor
{ VENDOR_EMBER, "SmartPlug", emberMacPrefix }, // Heiman smart plug
{ VENDOR_120B, "WarningDevice", emberMacPrefix }, // Heiman siren
{ VENDOR_LUTRON, "LZL4BWHL01", lutronMacPrefix }, // Lutron LZL-4B-WH-L01 Connected Bulb Remote
{ 0, 0, 0 }
};
int TaskItem::_taskCounter = 1; // static rolling taskcounter
ApiRequest::ApiRequest(const QHttpRequestHeader &h, const QStringList &p, QTcpSocket *s, const QString &c) :
hdr(h), path(p), sock(s), content(c), version(ApiVersion_1), strict(false)
{
if (hdr.hasKey("Accept"))
{
if (hdr.value("Accept").contains("vnd.ddel.v1"))
{
version = ApiVersion_1_DDEL;
}
}
// some client may not be prepared for some responses
if (hdr.hasKey(QLatin1String("User-Agent")))
{
QString ua = hdr.value(QLatin1String("User-Agent"));
if (ua.startsWith(QLatin1String("iConnect")))
{
strict = true;
}
}
}
/*! Returns the apikey of a request or a empty string if not available
*/
QString ApiRequest::apikey() const
{
if (path.length() > 1)
{
return path.at(1);
}
return QLatin1String("");
}
/*! Constructor for pimpl.
\param parent - the main plugin
*/
DeRestPluginPrivate::DeRestPluginPrivate(QObject *parent) :
QObject(parent)
{
pollManager = new PollManager(this);
databaseTimer = new QTimer(this);
databaseTimer->setSingleShot(true);
initEventQueue();
initResourceDescriptors();
connect(databaseTimer, SIGNAL(timeout()),
this, SLOT(saveDatabaseTimerFired()));
webSocketServer = 0;
gwScanner = new GatewayScanner(this);
connect(gwScanner, SIGNAL(foundGateway(QHostAddress,quint16,QString,QString)),
this, SLOT(foundGateway(QHostAddress,quint16,QString,QString)));
gwScanner->startScan();
QString dataPath = deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation);
db = 0;
saveDatabaseItems = 0;
saveDatabaseIdleTotalCounter = 0;
sqliteDatabaseName = dataPath + QLatin1String("/zll.db");
idleLimit = 0;
idleTotalCounter = IDLE_READ_LIMIT;
idleLastActivity = 0;
sensorIndIdleTotalCounter = 0;
queryTime = QTime::currentTime();
udpSock = 0;
haEndpoint = 0;
gwGroupSendDelay = deCONZ::appArgumentNumeric("--group-delay", GROUP_SEND_DELAY);
supportColorModeXyForGroups = false;
groupDeviceMembershipChecked = false;
gwLinkButton = false;
gwWebSocketNotifyAll = true;
// preallocate memory to get consistent pointers
nodes.reserve(150);
sensors.reserve(150);
fastProbeTimer = new QTimer(this);
fastProbeTimer->setInterval(500);
fastProbeTimer->setSingleShot(true);
connect(fastProbeTimer, SIGNAL(timeout()), this, SLOT(delayedFastEnddeviceProbe()));
apsCtrl = deCONZ::ApsController::instance();
DBG_Assert(apsCtrl != 0);
apsCtrl->setParameter(deCONZ::ParamOtauActive, 0);
// starttime reference counts from here
starttimeRef.start();
initConfig();
updateEtag(gwConfigEtag);
updateEtag(gwSensorsEtag);
updateEtag(gwGroupsEtag);
updateEtag(gwLightsEtag);
// set some default might be overwritten by database
gwAnnounceInterval = ANNOUNCE_INTERVAL;
gwAnnounceUrl = "http://dresden-light.appspot.com/discover";
inetDiscoveryManager = 0;
archProcess = 0;
zipProcess = 0;
// sensors
findSensorsState = FindSensorsIdle;
findSensorsTimeout = 0;
ttlDataBaseConnection = 0;
openDb();
initDb();
readDb();
closeDb();
initTimezone();
checkConsistency();
if (!gwUserParameter.contains("groupssequenceleft"))
{
gwUserParameter["groupssequenceleft"] = "[]";
}
if (!gwUserParameter.contains("groupssequenceright"))
{
gwUserParameter["groupssequenceright"] = "[]";
}
if (gwUuid.isEmpty())
{
generateGatewayUuid();
}
// create default group
Group group;
group.setAddress(0);
group.setName("All");
groups.push_back(group);
initUpnpDiscovery();
connect(apsCtrl, SIGNAL(apsdeDataConfirm(const deCONZ::ApsDataConfirm&)),
this, SLOT(apsdeDataConfirm(const deCONZ::ApsDataConfirm&)));
connect(apsCtrl, SIGNAL(apsdeDataIndication(const deCONZ::ApsDataIndication&)),
this, SLOT(apsdeDataIndication(const deCONZ::ApsDataIndication&)));
connect(apsCtrl, SIGNAL(nodeEvent(deCONZ::NodeEvent)),
this, SLOT(nodeEvent(deCONZ::NodeEvent)));
deCONZ::GreenPowerController *gpCtrl = deCONZ::GreenPowerController::instance();
if (gpCtrl)
{
bool ok =
connect(gpCtrl, SIGNAL(gpDataIndication(deCONZ::GpDataIndication)),
this, SLOT(gpDataIndication(deCONZ::GpDataIndication)));
DBG_Assert(ok);
}
taskTimer = new QTimer(this);
taskTimer->setSingleShot(false);
connect(taskTimer, SIGNAL(timeout()),
this, SLOT(processTasks()));
taskTimer->start(100);
groupTaskTimer = new QTimer(this);
groupTaskTimer->setSingleShot(false);
connect(groupTaskTimer, SIGNAL(timeout()),
this, SLOT(processGroupTasks()));
groupTaskTimer->start(250);
verifyRulesTimer = new QTimer(this);
verifyRulesTimer->setSingleShot(false);
verifyRulesTimer->setInterval(100);
connect(verifyRulesTimer, SIGNAL(timeout()),
this, SLOT(verifyRuleBindingsTimerFired()));
verifyRulesTimer->start();
fastRuleCheckTimer = new QTimer(this);
fastRuleCheckTimer->setInterval(5);
fastRuleCheckTimer->setSingleShot(true);
connect(fastRuleCheckTimer, SIGNAL(timeout()),
this, SLOT(fastRuleCheckTimerFired()));
checkSensorsTimer = new QTimer(this);
checkSensorsTimer->setSingleShot(false);
checkSensorsTimer->setInterval(CHECK_SENSOR_INTERVAL);
connect(checkSensorsTimer, SIGNAL(timeout()),
this, SLOT(checkSensorStateTimerFired()));
checkSensorsTimer->start();
sensorCheckFast = 0;
bindingTimer = new QTimer(this);
bindingTimer->setSingleShot(true);
bindingTimer->setInterval(1000);
connect(bindingTimer, SIGNAL(timeout()),
this, SLOT(bindingTimerFired()));
bindingTableReaderTimer = new QTimer(this);
bindingTableReaderTimer->setSingleShot(true);
bindingTableReaderTimer->setInterval(1000);
connect(bindingTableReaderTimer, SIGNAL(timeout()),
this, SLOT(bindingTableReaderTimerFired()));
bindingToRuleTimer = new QTimer(this);
bindingToRuleTimer->setSingleShot(true);
bindingToRuleTimer->setInterval(50);
connect(bindingToRuleTimer, SIGNAL(timeout()),
this, SLOT(bindingToRuleTimerFired()));
lockGatewayTimer = new QTimer(this);
lockGatewayTimer->setSingleShot(true);
connect(lockGatewayTimer, SIGNAL(timeout()),
this, SLOT(lockGatewayTimerFired()));
openClientTimer = new QTimer(this);
openClientTimer->setSingleShot(false);
connect(openClientTimer, SIGNAL(timeout()),
this, SLOT(openClientTimerFired()));
openClientTimer->start(1000);
resendPermitJoinTimer = new QTimer(this);
resendPermitJoinTimer->setSingleShot(true);
connect(resendPermitJoinTimer, SIGNAL(timeout()),
this, SLOT(resendPermitJoinTimerFired()));
quint16 wsPort = deCONZ::appArgumentNumeric(QLatin1String("--ws-port"), gwConfig["websocketport"].toUInt());
webSocketServer = new WebSocketServer(this, wsPort);
gwConfig["websocketport"] = webSocketServer->port();
initAuthentification();
initInternetDicovery();
initSchedules();
initPermitJoin();
initOtau();
initTouchlinkApi();
initChangeChannelApi();
initResetDeviceApi();
initFirmwareUpdate();
//restoreWifiState();
indexRulesTriggers();
QTimer::singleShot(3000, this, SLOT(initWiFi()));
}
/*! Deconstructor for pimpl.
*/
DeRestPluginPrivate::~DeRestPluginPrivate()
{
if (inetDiscoveryManager)
{
inetDiscoveryManager->deleteLater();
inetDiscoveryManager = 0;
}
}
/*! 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 DeRestPluginPrivate::apsdeDataIndication(const deCONZ::ApsDataIndication &ind)
{
Q_Q(DeRestPlugin);
if (!q->pluginActive())
{
return;
}
if ((ind.profileId() == HA_PROFILE_ID) || (ind.profileId() == ZLL_PROFILE_ID))
{
deCONZ::ZclFrame zclFrame;
{
QDataStream stream(ind.asdu());
stream.setByteOrder(QDataStream::LittleEndian);
zclFrame.readFromStream(stream);
}
TaskItem task;
switch (ind.clusterId())
{
case GROUP_CLUSTER_ID:
handleGroupClusterIndication(task, ind, zclFrame);
break;
case SCENE_CLUSTER_ID:
handleSceneClusterIndication(task, ind, zclFrame);
handleClusterIndicationGateways(ind, zclFrame);
break;
case OTAU_CLUSTER_ID:
otauDataIndication(ind, zclFrame);
break;
case COMMISSIONING_CLUSTER_ID:
handleCommissioningClusterIndication(task, ind, zclFrame);
break;
case LEVEL_CLUSTER_ID:
handleClusterIndicationGateways(ind, zclFrame);
break;
case ONOFF_CLUSTER_ID:
handleOnOffClusterIndication(task, ind, zclFrame);
handleClusterIndicationGateways(ind, zclFrame);
break;
case IAS_ZONE_CLUSTER_ID:
handleIasZoneClusterIndication(ind, zclFrame);
break;
case DE_CLUSTER_ID:
handleDEClusterIndication(ind, zclFrame);
break;
default:
{
}
break;
}
handleIndicationFindSensors(ind, zclFrame);
if (ind.dstAddressMode() == deCONZ::ApsGroupAddress || ind.clusterId() == VENDOR_CLUSTER_ID ||
!(zclFrame.frameControl() & deCONZ::ZclFCDirectionServerToClient) ||
(zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReportAttributesId))
{
Sensor *sensorNode = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());
if (!sensorNode && zclFrame.manufacturerCode() == VENDOR_PHILIPS)
{ // dimmer switch?
sensorNode = getSensorNodeForAddress(ind.srcAddress());
}
if (sensorNode)
{
sensorNode->rx();
sensorNode->incrementRxCounter();
ResourceItem *item = sensorNode->item(RConfigReachable);
if (item && !item->toBool())
{
item->setValue(true);
Event e(RSensors, RConfigReachable, sensorNode->id(), item);
enqueueEvent(e);
}
checkSensorButtonEvent(sensorNode, ind, zclFrame);
}
}
if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReportAttributesId)
{
handleZclAttributeReportIndication(ind, zclFrame);
}
else if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclConfigureReportingResponseId)
{
handleZclConfigureReportingResponseIndication(ind, zclFrame);
}
}
else if (ind.profileId() == ZDP_PROFILE_ID)
{
deCONZ::ZclFrame zclFrame; // dummy
switch (ind.clusterId())
{
case ZDP_NODE_DESCRIPTOR_RSP_CLID:
case ZDP_SIMPLE_DESCRIPTOR_RSP_CLID:
case ZDP_ACTIVE_ENDPOINTS_RSP_CLID:
{
handleIndicationFindSensors(ind, zclFrame);
}
break;
case ZDP_DEVICE_ANNCE_CLID:
{
handleDeviceAnnceIndication(ind);
handleIndicationFindSensors(ind, zclFrame);
}
break;
case ZDP_IEEE_ADDR_CLID:
{
handleIeeeAddressReqIndication(ind);
}
break;
case ZDP_NWK_ADDR_CLID:
{
handleNwkAddressReqIndication(ind);
}
break;
case ZDP_MGMT_LQI_RSP_CLID:
{
handleMgmtLqiRspIndication(ind);
}
break;
case ZDP_MGMT_BIND_RSP_CLID:
handleMgmtBindRspIndication(ind);
break;
case ZDP_BIND_RSP_CLID:
case ZDP_UNBIND_RSP_CLID:
handleBindAndUnbindRspIndication(ind);
break;
case ZDP_MGMT_LEAVE_RSP_CLID:
handleMgmtLeaveRspIndication(ind);
break;
default:
break;
}
handleZdpIndication(ind);
}
else if (ind.profileId() == DE_PROFILE_ID)
{
otauDataIndication(ind, deCONZ::ZclFrame());
}
else if (ind.profileId() == ATMEL_WSNDEMO_PROFILE_ID)
{
wsnDemoDataIndication(ind);
}
}
/*! 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 DeRestPluginPrivate::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf)
{
pollManager->apsdeDataConfirm(conf);
std::list<TaskItem>::iterator i = runningTasks.begin();
std::list<TaskItem>::iterator end = runningTasks.end();
for (;i != end; ++i)
{
TaskItem &task = *i;
if (task.req.id() != conf.id())
{
continue;
}
if (conf.dstAddressMode() == deCONZ::ApsNwkAddress &&
task.req.dstAddressMode() == deCONZ::ApsNwkAddress &&
conf.dstAddress().hasNwk() && task.req.dstAddress().hasNwk() &&
conf.dstAddress().nwk() != task.req.dstAddress().nwk())
{
DBG_Printf(DBG_INFO, "warn APSDE-DATA.confirm: 0x%02X nwk mismatch\n", conf.id());
//continue;
}
QDateTime now = QDateTime::currentDateTime();
if (conf.status() != deCONZ::ApsSuccessStatus)
{
DBG_Printf(DBG_INFO, "0x%016llX error APSDE-DATA.confirm: 0x%02X on task\n", task.req.dstAddress().ext(), conf.status());
}
else if (task.req.dstAddressMode() == deCONZ::ApsGroupAddress &&
(task.req.clusterId() == ONOFF_CLUSTER_ID ||
task.req.clusterId() == LEVEL_CLUSTER_ID ||
task.req.clusterId() == COLOR_CLUSTER_ID))
{
quint16 groupId = task.req.dstAddress().group();
quint16 attrId = 0x0000;
if (task.req.clusterId() == COLOR_CLUSTER_ID)
{
attrId = 0x0003; // currentX
}
for (LightNode &l : nodes)
{
if (!l.isAvailable() ||
!l.lastRx().isValid() /*||
l.manufacturerCode() == VENDOR_IKEA ||
l.manufacturerCode() == VENDOR_OSRAM ||
l.manufacturerCode() == VENDOR_OSRAM_STACK ||
l.manufacturer().startsWith(QLatin1String("IKEA")) ||
l.manufacturer().startsWith(QLatin1String("OSRAM"))*/)
{
continue;
}
// fast poll lights which don't support or have active ZCL reporting
const NodeValue &val = l.getZclValue(ONOFF_CLUSTER_ID, attrId);
if ((!val.timestampLastReport.isValid() || val.timestampLastReport.secsTo(now) > (60 * 5)) &&
isLightNodeInGroup(&l, groupId))
{
DBG_Printf(DBG_INFO_L2, "\t0x%016llX force poll\n", l.address().ext());
pollManager->poll(&l, now.addSecs(3));
}
}
}
else if (task.lightNode)
{
switch (task.taskType)
{
case TaskSendOnOffToggle:
case TaskSetLevel:
case TaskSetXyColor:
case TaskSetEnhancedHue:
case TaskSetSat:
case TaskSetColorTemperature:
case TaskSetHue:
case TaskSetHueAndSaturation:
case TaskIncColorTemperature:
{
DBG_Printf(DBG_INFO, "\t0x%016llX force poll (2)\n", task.lightNode->address().ext());
pollManager->poll(task.lightNode, now.addSecs(3));
}
break;
default:
break;
}
}
if (DBG_IsEnabled(DBG_INFO_L2))
{
DBG_Printf(DBG_INFO_L2, "Erase task req-id: %u, type: %d zcl seqno: %u send time %d, profileId: 0x%04X, clusterId: 0x%04X\n",
task.req.id(), task.taskType, task.zclFrame.sequenceNumber(), idleTotalCounter - task.sendTime, task.req.profileId(), task.req.clusterId());
}
runningTasks.erase(i);
processTasks();
break;
}
if (channelChangeApsRequestId == conf.id() && channelChangeState == CC_WaitConfirm)
{
channelChangeSendConfirm(conf.status() == deCONZ::ApsSuccessStatus);
}
else if (resetDeviceApsRequestId == conf.id() && resetDeviceState == ResetWaitConfirm)
{
resetDeviceSendConfirm(conf.status() == deCONZ::ApsSuccessStatus);
}
if (handleMgmtBindRspConfirm(conf))
{
return;
}
}
/*! Process incoming green power button event.
\param ind - the data indication
*/
void DeRestPluginPrivate::gpProcessButtonEvent(const deCONZ::GpDataIndication &ind)
{
/*
PTM 215Z DEMO
A0 B0
A1 B1
DeviceId 0x02 (On/Off Switch)
A0,B0 Press 0x64 Press 2 of 2
A0,B0 Release 0x65 Release 2 of 2
A0 0x10 Scene0 B0 0x22 Toggle
A1 0x11 Scene1 B1 0x12 Scene2
A1,B1 Press 0x62 Press 1 of 2
A1,B1 Release 0x63 Release 1 of 2
*/
Sensor *sensor = getSensorNodeForAddress(ind.gpdSrcId());
ResourceItem *item = sensor ? sensor->item(RStateButtonEvent) : 0;
if (!sensor || !item || sensor->deletedState() == Sensor::StateDeleted)
{
return;
}
updateSensorEtag(sensor);
sensor->updateStateTimestamp();
item->setValue(ind.gpdCommandId());
Event e(RSensors, RStateButtonEvent, sensor->id(), item);
enqueueEvent(e);
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
}
/*! Returns the number of tasks for a specific address.
\param address - the destination address
*/
int DeRestPluginPrivate::taskCountForAddress(const deCONZ::Address &address)
{
int count = 0;
{
std::list<TaskItem>::const_iterator i = tasks.begin();
std::list<TaskItem>::const_iterator end = tasks.end();
for (; i != end; ++i)
{
if (i->req.dstAddress() == address)
{
count++;
}
}
}
{
std::list<TaskItem>::const_iterator i = runningTasks.begin();
std::list<TaskItem>::const_iterator end = runningTasks.end();
for (; i != end; ++i)
{
if (i->req.dstAddress() == address)
{
count++;
}
}
}
return count;
}
/*! Process incoming green power data frame.
\param ind - the data indication
*/
void DeRestPluginPrivate::gpDataIndication(const deCONZ::GpDataIndication &ind)
{
switch (ind.gpdCommandId())
{
case deCONZ::GpCommandIdScene0:
case deCONZ::GpCommandIdScene1:
case deCONZ::GpCommandIdScene2:
case deCONZ::GpCommandIdScene3:
case deCONZ::GpCommandIdScene4:
case deCONZ::GpCommandIdScene5:
case deCONZ::GpCommandIdScene6:
case deCONZ::GpCommandIdScene7:
case deCONZ::GpCommandIdScene8:
case deCONZ::GpCommandIdScene9:
case deCONZ::GpCommandIdScene10:
case deCONZ::GpCommandIdScene11:
case deCONZ::GpCommandIdScene12:
case deCONZ::GpCommandIdScene13:
case deCONZ::GpCommandIdScene14:
case deCONZ::GpCommandIdScene15:
case deCONZ::GpCommandIdOn:
case deCONZ::GpCommandIdOff:
case deCONZ::GpCommandIdToggle:
case deCONZ::GpCommandIdRelease:
case deCONZ::GpCommandIdPress1Of1:
case deCONZ::GpCommandIdRelease1Of1:
case deCONZ::GpCommandIdPress1Of2:
case deCONZ::GpCommandIdRelease1Of2:
case deCONZ::GpCommandIdPress2Of2:
case deCONZ::GpCommandIdRelease2Of2:
{
gpProcessButtonEvent(ind);
}
break;
case deCONZ::GpCommandIdCommissioning:
{
// 1 8-bit enum GPD DeviceID
// 1 8-bit bmp Options
// 0/1 8-bit bmp Extended Options
// 0/16 Security Key GPD Key
// 0/4 u32 GPD Key MIC
// 0/4 u32 GPD outgoing counter
quint8 gpdDeviceId;
quint8 gpdKey[16];
quint32 gpdMIC = 0;
quint32 gpdOutgoingCounter = 0;
deCONZ::GPCommissioningOptions options;
deCONZ::GpExtCommissioningOptions extOptions;
options.byte = 0;
extOptions.byte = 0;
QDataStream stream(ind.payload());
stream.setByteOrder(QDataStream::LittleEndian);
if (stream.atEnd()) { return; }
stream >> gpdDeviceId;
if (stream.atEnd()) { return; }
stream >> options.byte;
if (options.bits.extOptionsField)
{
if (stream.atEnd()) { return; }
stream >> extOptions.byte;
}
if (extOptions.bits.gpdKeyPresent)
{
for (int i = 0; i < 16; i++)
{
if (stream.atEnd()) { return; }
stream >> gpdKey[i];
}
if (extOptions.bits.gpdKeyEncryption)
{
// TODO decrypt key
if (stream.atEnd()) { return; }
stream >> gpdMIC;
}
}
switch (extOptions.bits.securityLevelCapabilities)
{
case 0:
default:
break;
}
if (extOptions.bits.gpdOutgoingCounterPresent)
{
if (stream.atEnd()) { return; }
stream >> gpdOutgoingCounter;
}
SensorFingerprint fp;
fp.endpoint = GREEN_POWER_ENDPOINT;
fp.deviceId = gpdDeviceId;
fp.profileId = GP_PROFILE_ID;
fp.outClusters.push_back(GREEN_POWER_CLUSTER_ID);
Sensor *sensor = getSensorNodeForFingerPrint(ind.gpdSrcId(), fp, "ZGPSwitch");
if (!sensor)
{
if (findSensorsState != FindSensorsActive)
{
return;
}
// create new sensor
Sensor sensorNode;
if (gpdDeviceId == deCONZ::GpDeviceIdOnOffSwitch)
{
sensorNode.setType("ZGPSwitch");
sensorNode.setModelId("ZGPSWITCH");
sensorNode.setManufacturer("Philips");
sensorNode.setSwVersion("1.0");
}
else
{
DBG_Printf(DBG_INFO, "unsupported green power device 0x%02X\n", gpdDeviceId);
return;
}
sensorNode.address().setExt(ind.gpdSrcId());
sensorNode.fingerPrint() = fp;
sensorNode.setUniqueId(generateUniqueId(sensorNode.address().ext(), sensorNode.fingerPrint().endpoint, GREEN_POWER_CLUSTER_ID));
sensorNode.setMode(Sensor::ModeNone);
ResourceItem *item;
item = sensorNode.item(RConfigOn);
item->setValue(true);
item = sensorNode.addItem(DataTypeInt32, RStateButtonEvent);
item->setValue(ind.gpdCommandId());
if (sensorNode.id().isEmpty())
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
}
if (sensorNode.name().isEmpty())
{
sensorNode.setName(QString("Hue Tap %2").arg(sensorNode.id()));
}
checkSensorGroup(&sensorNode);
DBG_Printf(DBG_INFO, "SensorNode %u: %s added\n", sensorNode.id().toUInt(), qPrintable(sensorNode.name()));
updateSensorEtag(&sensorNode);
sensorNode.setNeedSaveDatabase(true);
sensors.push_back(sensorNode);
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
queSaveDb(DB_SENSORS , DB_SHORT_SAVE_DELAY);
}
else if (sensor && sensor->deletedState() == Sensor::StateDeleted)
{
if (findSensorsState == FindSensorsActive)
{
sensor->setDeletedState(Sensor::StateNormal);
checkSensorGroup(sensor);
sensor->setNeedSaveDatabase(true);
DBG_Printf(DBG_INFO, "SensorNode %u: %s reactivated\n", sensor->id().toUInt(), qPrintable(sensor->name()));
updateSensorEtag(sensor);
Event e(RSensors, REventAdded, sensor->id());
enqueueEvent(e);
queSaveDb(DB_SENSORS , DB_SHORT_SAVE_DELAY);
}
}
else
{
DBG_Printf(DBG_INFO, "SensorNode %s already known\n", qPrintable(sensor->name()));
}
}
break;
default:
break;
}
}
/*! Returns true if the ZigBee network is connected.
*/
bool DeRestPluginPrivate::isInNetwork()
{
if (apsCtrl)
{
return (apsCtrl->networkState() == deCONZ::InNetwork);
}
return false;
}
/*! Creates a error map used in JSON response.
\param id - error id
\param ressource example: "/lights/2"
\param description example: "resource, /lights/2, not available"
\return the map
*/
QVariantMap DeRestPluginPrivate::errorToMap(int id, const QString &ressource, const QString &description)
{
QVariantMap map;
QVariantMap error;
error["type"] = (double)id;
error["address"] = ressource;
error["description"] = description;
map["error"] = error;