-
Notifications
You must be signed in to change notification settings - Fork 505
/
rest_devices.cpp
1361 lines (1122 loc) · 38.7 KB
/
rest_devices.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) 2013-2024 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 <QString>
#include <QVariantMap>
#include <QProcess>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "product_match.h"
#include "database.h"
#include "device_descriptions.h"
#include "device_ddf_bundle.h"
#include "deconz/u_assert.h"
#include "deconz/u_sstream_ex.h"
#include "deconz/u_memory.h"
#include "rest_devices.h"
#include "utils/scratchmem.h"
#include "json.h"
#include "crypto/mmohash.h"
#include "utils/ArduinoJson.h"
#include "utils/utils.h"
using JsonDoc = StaticJsonDocument<1024 * 1024 * 2>; // 2 megabytes
static void putJsonQVariantValue(JsonObject &obj, std::string key, const QVariant &value);
static void putJsonArrayQVariantValue(JsonArray &arr, const QVariant &value);
static RestDevicesPrivate *priv_;
class RestDevicesPrivate
{
public:
JsonDoc json;
char jsonBuffer[1024 * 1024];
};
RestDevices::RestDevices(QObject *parent) :
QObject(parent)
{
d = new RestDevicesPrivate;
priv_ = d;
plugin = qobject_cast<DeRestPluginPrivate*>(parent);
Q_ASSERT(plugin);
}
RestDevices::~RestDevices()
{
priv_ = nullptr;
delete d;
}
/*! Devices REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int RestDevices::handleApi(const ApiRequest &req, ApiResponse &rsp)
{
// GET /api/<apikey>/devices
if (req.hdr.pathComponentsCount() == 3 && req.hdr.httpMethod() == HttpGet)
{
return getAllDevices(req, rsp);
}
// GET /api/<apikey>/devices/<uniqueid>
else if (req.hdr.pathComponentsCount() == 4 && req.hdr.httpMethod() == HttpGet)
{
return getDevice(req, rsp);
}
// PUT /api/<apikey>/devices/<uniqueid>/ddf/reload
else if (req.path.size() == 6 && req.hdr.method() == QLatin1String("PUT") && req.path[4] == QLatin1String("ddf") && req.path[5] == QLatin1String("reload"))
{
return putDeviceReloadDDF(req, rsp);
}
// PUT /api/<apikey>/devices/<uniqueid>/ddf/policy
else if (req.path.size() == 6 && req.hdr.method() == QLatin1String("PUT") && req.path[4] == QLatin1String("ddf") && req.path[5] == QLatin1String("policy"))
{
return putDeviceSetDDFPolicy(req, rsp);
}
// GET /api/<apikey>/devices/<uniqueid>/ddf
else if (req.hdr.pathComponentsCount() == 5 && req.hdr.httpMethod() == HttpGet && req.hdr.pathAt(4) == QLatin1String("ddf"))
{
return getDeviceDDF(req, rsp);
}
// GET /api/<apikey>/devices/<uniqueid>/ddffull
else if (req.hdr.pathComponentsCount() == 5 && req.hdr.httpMethod() == HttpGet && req.hdr.pathAt(4) == QLatin1String("ddffull"))
{
return getDeviceDDF(req, rsp);
}
// GET /api/<apikey>/devices/<uniuqueid>/introspect
else if (req.hdr.pathComponentsCount() == 5 && req.hdr.httpMethod() == HttpGet && req.hdr.pathAt(4) == QLatin1String("introspect"))
{
return RIS_GetDeviceIntrospect(req, rsp);
}
// GET /api/<apikey>/devices/<uniqueid>/[<prefix>/]<item>/introspect
else if (req.hdr.pathComponentsCount() > 5 && req.hdr.httpMethod() == HttpGet &&
req.hdr.pathAt(req.hdr.pathComponentsCount() - 1) == QLatin1String("introspect"))
{
return RIS_GetDeviceItemIntrospect(req, rsp);
}
// PUT /api/<apikey>/devices/<uniqueid>/installcode
else if (req.hdr.pathComponentsCount() == 5 && req.hdr.httpMethod() == HttpPut && req.hdr.pathAt(4) == QLatin1String("installcode"))
{
return putDeviceInstallCode(req, rsp);
}
return REQ_NOT_HANDLED;
}
static DeviceKey getDeviceKey(QLatin1String uniqueid)
{
DeviceKey result = 0;
const char *str = uniqueid.data();
if (uniqueid.size() < 23)
return result;
// 00:11:22:33:44:55:66:77
for (int pos = 0; pos < 23; pos++)
{
uint64_t ch = (unsigned)str[pos];
if (ch == ':' && (pos % 3) == 2) // ensure color only every 3rd pos
continue;
result <<= 4;
if (ch >= '0' && ch <= '9') ch = ch - '0';
else if (ch >= 'a' && ch <= 'f') ch = (ch - 'a') + 10;
else if (ch >= 'A' && ch <= 'F') ch = (ch - 'A') + 10;
else
{
result = 0;
break;
}
result |= (ch & 0x0F);
}
return result;
}
/*! Deletes a Sensor as a side effect it will be removed from the REST API
and a ZDP reset will be send if possible.
*/
bool deleteSensor(Sensor *sensor, DeRestPluginPrivate *plugin)
{
if (sensor && plugin && sensor->deletedState() == Sensor::StateNormal)
{
sensor->setDeletedState(Sensor::StateDeleted);
sensor->setNeedSaveDatabase(true);
sensor->setResetRetryCount(10);
enqueueEvent(Event(sensor->prefix(), REventDeleted, sensor->id()));
return true;
}
return false;
}
/*! Deletes a LightNode as a side effect it will be removed from the REST API
and a ZDP reset will be send if possible.
*/
bool deleteLight(LightNode *lightNode, DeRestPluginPrivate *plugin)
{
if (lightNode && plugin && lightNode->state() == LightNode::StateNormal)
{
lightNode->setState(LightNode::StateDeleted);
lightNode->setResetRetryCount(10);
lightNode->setNeedSaveDatabase(true);
// delete all group membership from light (todo this is messy)
for (auto &group : lightNode->groups())
{
//delete Light from all scenes.
plugin->deleteLightFromScenes(lightNode->id(), group.id);
//delete Light from all groups
group.actions &= ~GroupInfo::ActionAddToGroup;
group.actions |= GroupInfo::ActionRemoveFromGroup;
if (group.state != GroupInfo::StateNotInGroup)
{
group.state = GroupInfo::StateNotInGroup;
}
}
enqueueEvent(Event(lightNode->prefix(), REventDeleted, lightNode->id()));
return true;
}
return false;
}
/*! Deletes all resources related to a device from the REST API.
*/
bool RestDevices::deleteDevice(quint64 extAddr)
{
int count = 0;
for (auto &sensor : plugin->sensors)
{
if (sensor.address().ext() == extAddr && deleteSensor(&sensor, plugin))
{
count++;
}
}
for (auto &lightNode : plugin->nodes)
{
if (lightNode.address().ext() == extAddr && deleteLight(&lightNode, plugin))
{
count++;
}
}
if (count > 0)
{
plugin->queSaveDb(DB_SENSORS | DB_LIGHTS | DB_GROUPS | DB_SCENES, DB_SHORT_SAVE_DELAY);
}
// delete device entry, regardless if REST resources exists
plugin->deleteDeviceDb(generateUniqueId(extAddr, 0, 0));
enqueueEvent(Event(RDevices, REventDeleted, 0, extAddr));
return count > 0;
}
void RestDevices::handleEvent(const Event &event)
{
if (event.resource() == RDevices && event.what() == REventDeleted)
{
DEV_RemoveDevice(plugin->m_devices, event.deviceKey());
}
}
/*! GET /api/<apikey>/devices
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int RestDevices::getAllDevices(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req)
rsp.httpStatus = HttpStatusOk;
for (const auto &d : plugin->m_devices)
{
Q_ASSERT(d);
rsp.list.push_back(d->item(RAttrUniqueId)->toString());
}
if (rsp.list.isEmpty())
{
rsp.str = QLatin1String("[]"); // return empty list
}
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/devices/<uniqueid>
\return REQ_READY_SEND
REQ_NOT_HANDLED
Unstable API to experiment: don't use in production!
*/
int RestDevices::getDevice(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 4);
const auto deviceKey = extAddressFromUniqueId(req.hdr.pathAt(3));
Device *device = DEV_GetDevice(plugin->m_devices, deviceKey);
rsp.httpStatus = device ? HttpStatusOk : HttpStatusNotFound;
if (!device)
{
return REQ_READY_SEND;
}
const DeviceDescription &ddf = plugin->deviceDescriptions->get(device);
if (ddf.isValid())
{
rsp.map["productid"] = ddf.product;
}
{
const ResourceItem *ddfPolicyItem = device->item(RAttrDdfPolicy);
if (ddfPolicyItem)
{
rsp.map["ddf_policy"] = ddfPolicyItem->toString();
}
}
if (ddf.storageLocation == deCONZ::DdfBundleLocation || ddf.storageLocation == deCONZ::DdfBundleUserLocation)
{
const ResourceItem *ddfHashItem = device->item(RAttrDdfHash);
if (ddfHashItem && ddfHashItem->toCString()[0] != '\0')
{
rsp.map["ddf_hash"] = ddfHashItem->toString();
}
}
QVariantList subDevices;
for (const auto &sub : device->subDevices())
{
QVariantMap map;
for (int i = 0; i < sub->itemCount(); i++)
{
auto *item = sub->itemForIndex(i);
Q_ASSERT(item);
if (item->descriptor().suffix == RStateLastUpdated ||
item->descriptor().suffix == RAttrId)
{
continue;
}
if (!item->isPublic())
{
continue;
}
const auto ls = QString(QLatin1String(item->descriptor().suffix)).split(QLatin1Char('/'));
if (ls.size() == 2)
{
if (item->descriptor().suffix == RAttrLastSeen || item->descriptor().suffix == RAttrLastAnnounced ||
item->descriptor().suffix == RAttrManufacturerName || item->descriptor().suffix == RAttrModelId ||
item->descriptor().suffix == RAttrSwVersion || item->descriptor().suffix == RAttrName)
{
if (!rsp.map.contains(ls.at(1)))
{
rsp.map[ls.at(1)] = item->toString(); // top level attribute
}
}
else if (ls.at(0) == QLatin1String("attr"))
{
map[ls.at(1)] = item->toVariant(); // sub device top level attribute
}
else
{
QVariantMap m2;
if (map.contains(ls.at(0)))
{
m2 = map[ls.at(0)].toMap();
}
QVariantMap itemMap;
itemMap[QLatin1String("value")] = item->toVariant();
QDateTime dt = item->lastChanged().isValid() ? item->lastChanged() : item->lastSet();
// UTC in msec resolution
dt.setOffsetFromUtc(0);
itemMap[QLatin1String("lastupdated")] = dt.toString(QLatin1String("yyyy-MM-ddTHH:mm:ssZ"));
m2[ls.at(1)] = itemMap;
map[ls.at(0)] = m2;
}
}
}
subDevices.push_back(map);
}
rsp.map["uniqueid"] = device->item(RAttrUniqueId)->toString();
rsp.map["subdevices"] = subDevices;
return REQ_READY_SEND;
}
static void putJsonArrayQVariantValue(JsonArray &arr, const QVariant &value)
{
if (value.type() == QVariant::String)
{
arr.add(value.toString().toStdString());
}
else if (value.type() == QVariant::Bool)
{
arr.add(value.toBool());
}
else if (value.type() == QVariant::Double)
{
arr.add(value.toDouble());
}
else if (value.type() == QVariant::Int)
{
arr.add(value.toInt());
}
else if (value.type() == QVariant::UInt)
{
arr.add(value.toUInt());
}
else if (value.type() == QVariant::ULongLong)
{
arr.add(uint64_t(value.toULongLong()));
}
else if (value.type() == QVariant::LongLong)
{
arr.add(int64_t(value.toLongLong()));
}
else if (value.type() == QVariant::List)
{
JsonArray arr1 = arr.createNestedArray();
const QVariantList ls = value.toList();
for (const auto &v : ls)
{
putJsonArrayQVariantValue(arr1, v);
}
}
else if (value.type() == QVariant::Map)
{
JsonObject obj1 = arr.createNestedObject();
const QVariantMap map = value.toMap();
auto i = map.constBegin();
const auto end = map.constEnd();
for (; i != end; ++i)
{
putJsonQVariantValue(obj1, i.key().toStdString(), i.value());
}
}
else
{
DBG_Printf(DBG_DDF, "DDF TODO %s:%d arr add type: %s\n", __FILE__, __LINE__, QVariant::typeToName(value.type()));
}
}
static void putJsonQVariantValue(JsonObject &obj, std::string key, const QVariant &value)
{
if (value.type() == QVariant::String)
{
obj[key] = value.toString().toStdString();
}
else if (value.type() == QVariant::Bool)
{
obj[key] = value.toBool();
}
else if (value.type() == QVariant::Double)
{
obj[key] = value.toDouble();
}
else if (value.type() == QVariant::Int)
{
obj[key] = value.toInt();
}
else if (value.type() == QVariant::UInt)
{
obj[key] = value.toUInt();
}
else if (value.type() == QVariant::ULongLong)
{
obj[key] = uint64_t(value.toULongLong());
}
else if (value.type() == QVariant::LongLong)
{
obj[key] = int64_t(value.toLongLong());
}
else if (value.type() == QVariant::List)
{
JsonArray arr = obj.createNestedArray(key);
const QVariantList ls = value.toList();
for (const auto &v : ls)
{
putJsonArrayQVariantValue(arr, v);
}
}
else if (value.type() == QVariant::Map)
{
JsonObject obj1 = obj.createNestedObject(key);
const QVariantMap map = value.toMap();
auto i = map.constBegin();
const auto end = map.constEnd();
for (; i != end; ++i)
{
putJsonQVariantValue(obj1, i.key().toStdString(), i.value());
}
}
else
{
DBG_Printf(DBG_DDF, "DDF TODO %s:%d obj.%s type: %s\n", __FILE__, __LINE__, key.c_str(), QVariant::typeToName(value.type()));
}
}
static void putItemParameter(JsonObject &item, const char *name, const QVariantMap ¶m)
{
JsonObject parse = item.createNestedObject(name);
const auto end = param.constEnd();
for (auto cur = param.constBegin(); cur != end; cur++)
{
if (cur.key() == QLatin1String("eval"))
{
// no script cached 'eval' value
if (!param.contains(QLatin1String("script")))
{
putJsonQVariantValue(parse, "eval", cur.value());
}
}
else
{
putJsonQVariantValue(parse, cur.key().toStdString(), cur.value());
}
}
}
bool ddfSerializeV1(JsonDoc &doc, const DeviceDescription &ddf, char *buf, size_t bufsize, bool ddfFull, bool prettyPrint)
{
doc.clear();
doc["schema"] = "devcap1.schema.json";
if (ddf.manufacturerNames.size() == 1)
{
doc["manufacturername"] = ddf.manufacturerNames.front().toStdString();
}
else
{
JsonArray arr = doc.createNestedArray("manufacturername");
for (const QString &i : ddf.manufacturerNames)
{
arr.add(i.toStdString());
}
}
if (ddf.modelIds.size() == 1)
{
doc["modelid"] = ddf.modelIds.front().toStdString();
}
else
{
JsonArray arr = doc.createNestedArray("modelid");
for (const QString &i : ddf.modelIds)
{
arr.add(i.toStdString());
}
}
if (!ddf.vendor.isEmpty())
{
doc["vendor"] = ddf.vendor.toStdString();
}
if (!ddf.product.isEmpty())
{
doc["product"] = ddf.product.toStdString();
}
if (ddf.sleeper >= 0)
{
doc["sleeper"] = ddf.sleeper > 0;
}
doc["status"] = ddf.status.toStdString();
if (!ddf.matchExpr.isEmpty())
{
doc["matchexpr"] = ddf.matchExpr.toStdString();
}
if (!ddf.path.isEmpty())
{
int idx = ddf.path.indexOf(QLatin1String("/devices/"));
if (idx >= 0)
{
doc["path"] = ddf.path.mid(idx).toStdString();
}
}
{
JsonArray subDevices = doc.createNestedArray("subdevices");
for (const DeviceDescription::SubDevice &sub : ddf.subDevices)
{
JsonObject subDevice = subDevices.createNestedObject();
subDevice["type"] = sub.type.toStdString();
subDevice["restapi"] = sub.restApi.toStdString();
JsonArray uuid = subDevice.createNestedArray("uuid");
for (const QString &i : sub.uniqueId)
{
uuid.add(i.toStdString());
}
if (!sub.meta.isEmpty())
{
putJsonQVariantValue(subDevice, "meta", sub.meta);
}
if (isValid(sub.fingerPrint))
{
// "fingerprint": { "profile": "0x0104", "device": "0x0107", "endpoint": "0x02", "in": ["0x0000", "0x0001", "0x0402"] },
char buf[16];
JsonObject fp = subDevice.createNestedObject("fingerprint");
snprintf(buf, sizeof(buf), "0x%04X", sub.fingerPrint.profileId);
fp["profile"] = std::string(buf);
snprintf(buf, sizeof(buf), "0x%04X", sub.fingerPrint.deviceId);
fp["device"] = std::string(buf);
snprintf(buf, sizeof(buf), "0x%02X", sub.fingerPrint.endpoint);
fp["endpoint"] = std::string(buf);
if (!sub.fingerPrint.inClusters.empty())
{
JsonArray inClusters = fp.createNestedArray("in");
for (const auto clusterId : sub.fingerPrint.inClusters)
{
snprintf(buf, sizeof(buf), "0x%04X", clusterId);
inClusters.add(std::string(buf));
}
}
if (!sub.fingerPrint.outClusters.empty())
{
JsonArray outClusters = fp.createNestedArray("out");
for (const auto clusterId : sub.fingerPrint.outClusters)
{
snprintf(buf, sizeof(buf), "0x%04X", clusterId);
outClusters.add(std::string(buf));
}
}
}
JsonArray items = subDevice.createNestedArray("items");
for (const DeviceDescription::Item &i : sub.items)
{
JsonObject item = items.createNestedObject();
if (i.isImplicit && !ddfFull)
{
item["name"] = i.name.c_str();
continue;
}
item["name"] = i.name.c_str();
if (!i.isPublic) { item["public"] = false; }
if (i.awake) { item["awake"] = true; }
if (!i.description.isEmpty())
{
item["description"] = i.description.toStdString();
}
if (i.refreshInterval > 0)
{
item["refresh.interval"] = i.refreshInterval;
}
if (!i.isStatic)
{
if (!i.readParameters.isNull() && (ddfFull || !i.isGenericRead)) { putItemParameter(item, "read", i.readParameters.toMap()); }
if (!i.writeParameters.isNull() && (ddfFull || !i.isGenericWrite)) { putItemParameter(item, "write", i.writeParameters.toMap()); }
if (!i.parseParameters.isNull() && (ddfFull || !i.isGenericParse)) { putItemParameter(item, "parse", i.parseParameters.toMap()); }
}
if (!i.defaultValue.isNull())
{
if (i.isStatic)
{
putJsonQVariantValue(item, "static", i.defaultValue);
}
else
{
putJsonQVariantValue(item, "default", i.defaultValue);
}
}
}
}
}
if (!ddf.bindings.empty())
{
JsonArray bindings = doc.createNestedArray("bindings");
for (const DDF_Binding &bnd : ddf.bindings)
{
JsonObject binding = bindings.createNestedObject();
if (bnd.isUnicastBinding) { binding["bind"] = "unicast"; }
else if (bnd.isGroupBinding)
{
binding["bind"] = "groupcast";
binding["config.group"] = bnd.configGroup;
}
binding["src.ep"] = bnd.srcEndpoint;
if (bnd.dstEndpoint > 0) { binding["dst.ep"] = bnd.dstEndpoint; }
char buf[16];
snprintf(buf, sizeof(buf), "0x%04X", bnd.clusterId);
binding["cl"] = std::string(buf);
if (!bnd.reporting.empty())
{
JsonArray reportings = binding.createNestedArray("report");
for (const DDF_ZclReport &rep: bnd.reporting)
{
JsonObject report = reportings.createNestedObject();
snprintf(buf, sizeof(buf), "0x%04X", rep.attributeId);
report["at"] = std::string(buf);
// TODO ZCLDB names
snprintf(buf, sizeof(buf), "0x%02X", rep.dataType);
report["dt"] = std::string(buf);
if (rep.manufacturerCode > 0)
{
snprintf(buf, sizeof(buf), "0x%04X", rep.manufacturerCode);
report["mf"] = std::string(buf);
}
report["min"] = rep.minInterval;
report["max"] = rep.maxInterval;
if (rep.reportableChange > 0)
{
snprintf(buf, sizeof(buf), "0x%08X", rep.reportableChange); // TODO proper length
report["change"] = std::string(buf);
}
}
}
}
}
size_t sz = 0;
if (prettyPrint)
{
sz = serializeJsonPretty(doc, buf, bufsize);
}
else
{
sz = serializeJson(doc, buf, bufsize);
}
U_ASSERT(sz < bufsize);
DBG_Printf(DBG_INFO, "JSON serialized size %d\n", int(sz));
return sz > 0 && sz < bufsize;
}
QString DDF_ToJsonPretty(const DeviceDescription &ddf)
{
QString result;
if (priv_ && ddfSerializeV1(priv_->json, ddf, priv_->jsonBuffer, sizeof(priv_->jsonBuffer), false, true))
{
result = priv_->jsonBuffer;
}
return result;
}
int RestDevices::getDeviceDDF(const ApiRequest &req, ApiResponse &rsp)
{
const auto deviceKey = extAddressFromUniqueId(req.hdr.pathAt(3));
bool ddfFull = req.hdr.pathAt(4) == QLatin1String("ddffull");
Device *device = DEV_GetDevice(plugin->m_devices, deviceKey);
rsp.httpStatus = device ? HttpStatusOk : HttpStatusNotFound;
if (!device)
{
return REQ_READY_SEND;
}
DeviceDescription ddf = DeviceDescriptions::instance()->get(device);
if (ddf.isValid())
{
if (ddf.bindings.empty())
{
ddf.bindings = device->bindings();
}
if (ddfSerializeV1(d->json, ddf, d->jsonBuffer, sizeof(d->jsonBuffer), ddfFull, false))
{
rsp.str = d->jsonBuffer;
}
else
{
// error
}
}
else
{
rsp.httpStatus = HttpStatusNotFound;
rsp.str = QLatin1String("{}");
}
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/devices/<uniqueid>/introspect
\return REQ_READY_SEND
REQ_NOT_HANDLED
Unstable API to experiment: don't use in production!
*/
int RIS_GetDeviceIntrospect(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req)
rsp.str = QLatin1String("{\"introspect\": false}");
return REQ_READY_SEND;
}
/*! Returns string form of a ApiDataType.
*/
QLatin1String RIS_DataTypeToString(ApiDataType type)
{
static const std::array<QLatin1String, 14> map = {
QLatin1String("unknown"),
QLatin1String("bool"),
QLatin1String("uint8"),
QLatin1String("uint16"),
QLatin1String("uint32"),
QLatin1String("uint64"),
QLatin1String("int8"),
QLatin1String("int16"),
QLatin1String("int32"),
QLatin1String("int64"),
QLatin1String("double"),
QLatin1String("string"),
QLatin1String("time"),
QLatin1String("timepattern")
};
if (type < map.size())
{
return map[type];
}
return map[0];
}
/*! Returns string form of \c state/buttonevent action part.
*/
QLatin1String RIS_ButtonEventActionToString(int buttonevent)
{
const uint action = buttonevent % 1000;
static std::array<QLatin1String, 11> map = {
QLatin1String("INITIAL_PRESS"),
QLatin1String("HOLD"),
QLatin1String("SHORT_RELEASE"),
QLatin1String("LONG_RELEASE"),
QLatin1String("DOUBLE_PRESS"),
QLatin1String("TREBLE_PRESS"),
QLatin1String("QUADRUPLE_PRESS"),
QLatin1String("SHAKE"),
QLatin1String("DROP"),
QLatin1String("TILT"),
QLatin1String("MANY_PRESS")
};
if (action < map.size())
{
return map[action];
}
return QLatin1String("UNKNOWN");
}
/*! Returns generic introspection for a \c ResourceItem.
*/
QVariantMap RIS_IntrospectGenericItem(const ResourceItemDescriptor &rid)
{
QVariantMap result;
result[QLatin1String("type")] = RIS_DataTypeToString(rid.type);
if (rid.validMin != 0 || rid.validMax != 0)
{
result[QLatin1String("minval")] = rid.validMin;
result[QLatin1String("maxval")] = rid.validMax;
}
return result;
}
/*! Returns introspection for \c state/buttonevent.
*/
QVariantMap RIS_IntrospectButtonEventItem(const ResourceItemDescriptor &rid, const Resource *r)
{
QVariantMap result = RIS_IntrospectGenericItem(rid);
Q_ASSERT(r->prefix() == RSensors);
const auto *sensor = static_cast<const Sensor*>(r);
if (!sensor)
{
return result;
}
const deCONZ::Node *node = getCoreNode(sensor->address().ext(), deCONZ::ApsController::instance());
if (!node)
{
return result;
}
// TODO dependency on plugin needs to be removed to make this testable
const auto &buttonMapButtons = plugin->buttonMeta;
const auto &buttonMapData = plugin->buttonMaps;
const auto &buttonMapForModelId = plugin->buttonProductMap;
const auto *buttonData = BM_ButtonMapForProduct(productHash(r), buttonMapData, buttonMapForModelId);
if (!buttonData)
{
return result;
}
int buttonBits = 0; // button 1 = 1 << 1, button 2 = 1 << 2 ...
{
QVariantMap values;
for (const auto &btn : buttonData->buttons)
{
const auto sd = std::find_if(node->simpleDescriptors().cbegin(), node->simpleDescriptors().cend(),
[&btn](const deCONZ::SimpleDescriptor &x){ return x.endpoint() == btn.endpoint; });
if (sd == node->simpleDescriptors().cend())
{
continue;
}
buttonBits |= 1 << int(btn.button / 1000);
QVariantMap m;
m[QLatin1String("button")] = int(btn.button / 1000);
m[QLatin1String("action")] = RIS_ButtonEventActionToString(btn.button);
values[QString::number(btn.button)] = m;
}
result[QLatin1String("values")] = values;
}
const auto buttonsMeta = std::find_if(buttonMapButtons.cbegin(), buttonMapButtons.cend(),
[buttonData](const auto &meta){ return meta.buttonMapRef.hash == buttonData->buttonMapRef.hash; });
QVariantMap buttons;
if (buttonsMeta != buttonMapButtons.cend())
{
for (const auto &button : buttonsMeta->buttons)
{
if (buttonBits & (1 << button.button))
{
QVariantMap m;
m[QLatin1String("name")] = button.name;
buttons[QString::number(button.button)] = m;
}
}
}
else // fallback if no "buttons" is defined in the button map, generate a generic one
{
for (int i = 1 ; i < 32; i++)
{
if (buttonBits & (1 << i))
{
QVariantMap m;
m[QLatin1String("name")] = QString("Button %1").arg(i);
buttons[QString::number(i)] = m;
}