forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest_sensors.cpp
2996 lines (2668 loc) · 109 KB
/
rest_sensors.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-2019 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 <QTextCodec>
#include <QTcpSocket>
#include <QUrlQuery>
#include <QVariantMap>
#include <QtCore/qmath.h>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "json.h"
/*! Sensors REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleSensorsApi(const ApiRequest &req, ApiResponse &rsp)
{
if (req.path[2] != QLatin1String("sensors"))
{
return REQ_NOT_HANDLED;
}
// GET /api/<apikey>/sensors
if ((req.path.size() == 3) && (req.hdr.method() == "GET"))
{
return getAllSensors(req, rsp);
}
// GET /api/<apikey>/sensors/new
else if ((req.path.size() == 4) && (req.hdr.method() == "GET") && (req.path[3] == "new"))
{
return getNewSensors(req, rsp);
}
// GET /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "GET"))
{
return getSensor(req, rsp);
}
// GET /api/<apikey>/sensors/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
else if ((req.path.size() == 5) && (req.hdr.method() == "GET") && (req.path[4] == "data"))
{
return getSensorData(req, rsp);
}
// POST /api/<apikey>/sensors
else if ((req.path.size() == 3) && (req.hdr.method() == "POST"))
{
bool ok;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
if (map.isEmpty())
{
return searchNewSensors(req, rsp);
}
else
{
return createSensor(req, rsp);
}
}
// PUT, PATCH /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH"))
{
return updateSensor(req, rsp);
}
// DELETE /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "DELETE"))
{
return deleteSensor(req, rsp);
}
// PUT, PATCH /api/<apikey>/sensors/<id>/config
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "config"))
{
return changeSensorConfig(req, rsp);
}
// PUT, PATCH /api/<apikey>/sensors/<id>/state
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "state"))
{
return changeSensorState(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! GET /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getAllSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
rsp.httpStatus = HttpStatusOk;
// handle ETag
if (req.hdr.hasKey("If-None-Match"))
{
QString etag = req.hdr.value("If-None-Match");
if (gwSensorsEtag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
std::vector<Sensor>::iterator i = sensors.begin();
std::vector<Sensor>::iterator end = sensors.end();
for (; i != end; ++i)
{
// ignore deleted sensors
if (i->deletedState() == Sensor::StateDeleted)
{
continue;
}
// ignore sensors without attached node
if (i->modelId().startsWith("FLS-NB") && !i->node())
{
continue;
}
if (i->modelId().isEmpty())
{
continue;
}
QVariantMap map;
if (sensorToMap(&*i, map, req))
{
rsp.map[i->id()] = map;
}
}
if (rsp.map.isEmpty())
{
rsp.str = "{}"; // return empty object
}
rsp.etag = gwSensorsEtag;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getSensor(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 4);
if (req.path.size() != 4)
{
return REQ_NOT_HANDLED;
}
const QString &id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
// handle ETag
if (req.hdr.hasKey("If-None-Match"))
{
QString etag = req.hdr.value("If-None-Match");
if (sensor->etag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
sensorToMap(sensor, rsp.map, req);
rsp.httpStatus = HttpStatusOk;
rsp.etag = sensor->etag;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getSensorData(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 5);
if (req.path.size() != 5)
{
return REQ_NOT_HANDLED;
}
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/").arg(id), QString("resource, /sensors/%1/, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
bool ok;
QUrl url(req.hdr.url());
QUrlQuery query(url);
const int maxRecords = query.queryItemValue(QLatin1String("maxrecords")).toInt(&ok);
if (!ok || maxRecords <= 0)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/maxrecords"), QString("invalid value, %1, for parameter, maxrecords").arg(query.queryItemValue("maxrecords"))));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
QString t = query.queryItemValue(QLatin1String("fromtime"));
QDateTime dt = QDateTime::fromString(t, QLatin1String("yyyy-MM-ddTHH:mm:ss"));
if (!dt.isValid())
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/fromtime"), QString("invalid value, %1, for parameter, fromtime").arg(query.queryItemValue("fromtime"))));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
const qint64 fromTime = dt.toMSecsSinceEpoch() / 1000;
openDb();
loadSensorDataFromDb(sensor, rsp.list, fromTime, maxRecords);
closeDb();
if (rsp.list.isEmpty())
{
rsp.str = QLatin1String("[]"); // return empty list
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! POST /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::createSensor(const ApiRequest &req, ApiResponse &rsp)
{
rsp.httpStatus = HttpStatusOk;
bool ok;
QVariant var = Json::parse(req.content, ok);
const QVariantMap map = var.toMap();
const QString type = map["type"].toString();
Sensor sensor;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
userActivity();
if (sensors.size() >= MAX_SENSORS)
{
rsp.list.append(errorToMap(ERR_SENSOR_LIST_FULL , QString("/sensors/"), QString("The Sensor List has reached its maximum capacity of %1 sensors").arg(MAX_SENSORS)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//check required parameter
if ((!(map.contains("name")) || !(map.contains("modelid")) || !(map.contains("swversion")) || !(map.contains("type")) || !(map.contains("uniqueid")) || !(map.contains("manufacturername"))))
{
rsp.list.append(errorToMap(ERR_MISSING_PARAMETER, QString("/sensors"), QString("invalid/missing parameters in body")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//check invalid parameter
const QStringList allowedAttributes = { "name", "modelid", "swversion", "type", "uniqueid", "manufacturername", "state", "config", "recycle" };
for (const QString &attr : map.keys())
{
if (!allowedAttributes.contains(attr))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(attr), QString("parameter, %1, not available").arg(attr)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (!type.startsWith(QLatin1String("CLIP")))
{
rsp.list.append(errorToMap(ERR_NOT_ALLOWED_SENSOR_TYPE, QString("/sensors"), QString("Not allowed to create sensor type")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItem *item = nullptr;
QVariantMap rspItem;
QVariantMap rspItemState;
// create a new sensor id
openDb();
sensor.setId(QString::number(getFreeSensorId()));
closeDb();
sensor.setName(map["name"].toString().trimmed());
sensor.setManufacturer(map["manufacturername"].toString());
sensor.setModelId(map["modelid"].toString());
sensor.setUniqueId(map["uniqueid"].toString());
sensor.setSwVersion(map["swversion"].toString());
sensor.setType(type);
if (getSensorNodeForUniqueId(sensor.uniqueId()))
{
rsp.list.append(errorToMap(ERR_DUPLICATE_EXIST, QString("/sensors"), QString("sensor with uniqueid, %1, already exists").arg(sensor.uniqueId())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (type == QLatin1String("CLIPAlarm")) { item = sensor.addItem(DataTypeBool, RStateAlarm); item->setValue(false); }
else if (type == QLatin1String("CLIPBattery")) { item = sensor.addItem(DataTypeUInt8, RStateBattery); item->setValue(100); }
else if (type == QLatin1String("CLIPCarbonMonoxide")) { item = sensor.addItem(DataTypeBool, RStateCarbonMonoxide); item->setValue(false); }
else if (type == QLatin1String("CLIPConsumption")) { item = sensor.addItem(DataTypeUInt64, RStateConsumption); item->setValue(0); }
else if (type == QLatin1String("CLIPDaylightOffset")) { item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0);
item = sensor.addItem(DataTypeString, RConfigMode);
item = sensor.addItem(DataTypeTime, RStateLocaltime); }
else if (type == QLatin1String("CLIPFire")) { item = sensor.addItem(DataTypeBool, RStateFire); item->setValue(false); }
else if (type == QLatin1String("CLIPGenericFlag")) { item = sensor.addItem(DataTypeBool, RStateFlag); item->setValue(false); }
else if (type == QLatin1String("CLIPGenericStatus")) { item = sensor.addItem(DataTypeInt32, RStateStatus); item->setValue(0); }
else if (type == QLatin1String("CLIPHumidity")) { item = sensor.addItem(DataTypeUInt16, RStateHumidity); item->setValue(0);
item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0); }
else if (type == QLatin1String("CLIPLightLevel")) { item = sensor.addItem(DataTypeUInt16, RStateLightLevel); item->setValue(0);
item = sensor.addItem(DataTypeUInt32, RStateLux); item->setValue(0);
item = sensor.addItem(DataTypeBool, RStateDark); item->setValue(true);
item = sensor.addItem(DataTypeBool, RStateDaylight); item->setValue(false);
item = sensor.addItem(DataTypeUInt16, RConfigTholdDark); item->setValue(R_THOLDDARK_DEFAULT);
item = sensor.addItem(DataTypeUInt16, RConfigTholdOffset); item->setValue(R_THOLDOFFSET_DEFAULT); }
else if (type == QLatin1String("CLIPOpenClose")) { item = sensor.addItem(DataTypeBool, RStateOpen); item->setValue(false); }
else if (type == QLatin1String("CLIPPower")) { item = sensor.addItem(DataTypeInt16, RStatePower); item->setValue(0);
item = sensor.addItem(DataTypeUInt16, RStateVoltage); item->setValue(0);
item = sensor.addItem(DataTypeUInt16, RStateCurrent); item->setValue(0); }
else if (type == QLatin1String("CLIPPresence")) { item = sensor.addItem(DataTypeBool, RStatePresence); item->setValue(false);
item = sensor.addItem(DataTypeUInt16, RConfigDuration); item->setValue(60); }
else if (type == QLatin1String("CLIPPressure")) { item = sensor.addItem(DataTypeInt16, RStatePressure); item->setValue(0); }
else if (type == QLatin1String("CLIPSwitch")) { item = sensor.addItem(DataTypeInt32, RStateButtonEvent); item->setValue(0); }
else if (type == QLatin1String("CLIPTemperature")) { item = sensor.addItem(DataTypeInt16, RStateTemperature); item->setValue(0);
item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0); }
else if (type == QLatin1String("CLIPVibration")) { item = sensor.addItem(DataTypeBool, RStateVibration); item->setValue(false); }
else if (type == QLatin1String("CLIPWater")) { item = sensor.addItem(DataTypeBool, RStateWater); item->setValue(false); }
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("invalid value, %1, for parameter, type").arg(type)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//setState optional
if (map.contains("state"))
{
//check invalid parameter
const QVariantMap state = map["state"].toMap();
const QStringList allowedKeys = { "alarm", "battery", "buttonevent", "carbonmonoxide", "consumption", "current", "fire", "flag", "humidity", "lightlevel", "localtime", "lowbattery",
"open", "presence", "pressure", "power", "status", "tampered", "temperature", "vibration", "voltage", "water" };
const QStringList optionalKeys = { "lowbattery", "tampered" };
for (const auto &key : state.keys())
{
if (!allowedKeys.contains(key))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(key), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItemDescriptor rid;
item = nullptr;
if (getResourceItemDescriptor(QString("state/%1").arg(key), rid))
{
item = sensor.item(rid.suffix);
if (!item && optionalKeys.contains(key))
{
item = sensor.addItem(rid.type, rid.suffix);
}
}
if (!item)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!item->setValue(state.value(key)))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/state"), QString("invalid value, %1, for parameter %2").arg(state.value(key).toString()).arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
item = sensor.item(RConfigOn);
item->setValue(true); // default
item = sensor.item(RConfigReachable);
item->setValue(true); //default
//setConfig optional
if (map.contains("config"))
{
//check invalid parameter
const QVariantMap config = map["config"].toMap();
const QStringList allowedKeys = { "battery", "duration", "delay", "mode", "offset", "on", "reachable", "url" };
const QStringList optionalKeys = { "battery", "url" };
for (const auto &key : config.keys())
{
if (!allowedKeys.contains(key))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(key), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItemDescriptor rid;
item = nullptr;
if (getResourceItemDescriptor(QString("config/%1").arg(key), rid))
{
item = sensor.item(rid.suffix);
if (!item && optionalKeys.contains(key))
{
item = sensor.addItem(rid.type, rid.suffix);
}
}
if (!item)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!item->setValue(config.value(key)))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/config"), QString("invalid value, %1, for parameter %2").arg(config.value(key).toString()).arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
updateSensorEtag(&sensor);
sensor.setNeedSaveDatabase(true);
sensors.push_back(sensor);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
rspItemState["id"] = sensor.id();
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::updateSensor(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
QString name;
bool ok;
bool error = false;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
if (req.sock)
{
userActivity();
}
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
for (; pi != pend; ++pi)
{
if (!((pi.key() == "name") || (pi.key() == "modelid") || (pi.key() == "swversion")
|| (pi.key() == "type") || (pi.key() == "uniqueid") || (pi.key() == "manufacturername")
|| (pi.key() == "state") || (pi.key() == "config")
|| (pi.key() == "mode" && (sensor->modelId() == "Lighting Switch" || sensor->modelId().startsWith(QLatin1String("SYMFONISK"))))))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(pi.key()), QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (map.contains("modelid"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/modelid"), QString("parameter, modelid, not modifiable")));
}
if (map.contains("swversion"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/swversion"), QString("parameter, swversion, not modifiable")));
}
if (map.contains("type"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/type"), QString("parameter, type, not modifiable")));
}
if (map.contains("uniqueid"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/uniqueid"), QString("parameter, uniqueid, not modifiable")));
}
if (map.contains("manufacturername"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/manufacturername"), QString("parameter, manufacturername, not modifiable")));
}
if (map.contains("state"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/state"), QString("parameter, state, not modifiable")));
}
if (error)
{
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (map.contains("name")) // optional
{
name = map["name"].toString().trimmed();
if ((map["name"].type() == QVariant::String) && !(name.isEmpty()) && (name.size() <= MAX_SENSOR_NAME_LENGTH))
{
if (sensor->name() != name)
{
sensor->setName(name);
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
Event e(RSensors, RAttrName, sensor->id(), sensor->item(RAttrName));
enqueueEvent(e);
}
if (!sensor->type().startsWith(QLatin1String("CLIP")))
{
pushSensorInfoToCore(sensor);
}
rspItemState[QString("/sensors/%1/name").arg(id)] = name;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/name").arg(id), QString("invalid value, %1, for parameter, /sensors/%2/name").arg(name).arg(id)));
rsp.httpStatus = HttpStatusBadRequest;
}
}
if (map.contains("mode")) // optional
{
Sensor::SensorMode mode = (Sensor::SensorMode)map["mode"].toUInt(&ok);
if (ok && (map["mode"].type() == QVariant::Double)
&& ((sensor->modelId() == "Lighting Switch" && (mode == Sensor::ModeScenes || mode == Sensor::ModeTwoGroups || mode == Sensor::ModeColorTemperature))
|| (sensor->modelId().startsWith(QLatin1String("SYMFONISK")) && (mode == Sensor::ModeScenes || mode == Sensor::ModeDimmer))))
{
if (sensor->mode() != mode)
{
sensor->setNeedSaveDatabase(true);
sensor->setMode(mode);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
}
rspItemState[QString("/sensors/%1/mode").arg(id)] = (double)mode;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
updateEtag(sensor->etag);
updateEtag(gwConfigEtag);
queSaveDb(DB_SENSORS | DB_GROUPS, DB_SHORT_SAVE_DELAY);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/mode").arg(id), QString("invalid value, %1, for parameter, /sensors/%2/mode").arg((int)mode).arg(id)));
rsp.httpStatus = HttpStatusBadRequest;
}
}
if (map.contains("config")) // optional
{
QStringList path = req.path;
path.append(QLatin1String("config"));
QString content = Json::serialize(map[QLatin1String("config")].toMap());
ApiRequest req2(req.hdr, path, NULL, content);
return changeSensorConfig(req2, rsp);
}
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>/config
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeSensorConfig(const ApiRequest &req, ApiResponse &rsp)
{
TaskItem task;
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
bool ok;
bool updated = false;
quint32 hostFlags = 0;
bool offsetUpdated = false;
qint16 offset = 0;
bool tholdUpdated = false;
uint8_t pendingMask = 0;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
// QRegExp latitude("^\\d{3,3}\\.\\d{4,4}(W|E)$");
// QRegExp longitude("^\\d{3,3}\\.\\d{4,4}(N|S)$");
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/config"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool isClip = sensor->type().startsWith(QLatin1String("CLIP"));
if (req.sock)
{
userActivity();
}
// set destination parameters
task.req.dstAddress() = sensor->address();
task.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
task.req.setDstEndpoint(sensor->fingerPrint().endpoint);
task.req.setSrcEndpoint(getSrcEndpoint(sensor, task.req));
task.req.setDstAddressMode(deCONZ::ApsExtAddress);
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
for (; pi != pend; ++pi)
{
ResourceItemDescriptor rid;
ResourceItem *item = 0;
if (getResourceItemDescriptor(QString("config/%1").arg(pi.key()), rid))
{
if (!isClip && (rid.suffix == RConfigBattery || rid.suffix == RConfigReachable))
{
// changing battery or reachable of zigbee sensors is not allowed, trigger error
}
else if (rid.suffix == RConfigPending || rid.suffix == RConfigSensitivityMax || rid.suffix == RConfigHostFlags)
{
// pending and sensitivitymax are read-only
}
//else if (rid.suffix == RConfigDuration && sensor->modelId() == QLatin1String("TRADFRI motion sensor"))
//{
// duration can be written for ikea motion sensor
// values 0, 60 — 600 will be replaced by hardware settings TODO error message
//}
else
{
item = sensor->item(rid.suffix);
}
if (item)
{
QVariant val = map[pi.key()];
if (rid.suffix == RConfigOffset)
{
offset -= item->toNumber();
}
if (rid.suffix == RConfigAlert)
{
if (val == "none")
{
task.identifyTime = 0;
}
else if (val == "select")
{
task.identifyTime = 2; // Hue lights don't react to 1.
}
else if (val == "lselect")
{
task.identifyTime = 15; // Default for Philips Hue bridge
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/alert").arg(id), QString("invalid value, %1, for parameter, alert").arg(val.toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
task.taskType = TaskIdentify;
taskToLocalData(task);
if (addTaskIdentify(task, task.identifyTime))
{
if (item->setValue(val))
{
rspItemState[QString("/sensors/%1/config/alert").arg(id)] = map["alert"];
rspItem["success"] = rspItemState;
if (item->lastChanged() == item->lastSet())
{
updated = true;
}
}
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/sensors/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else if (item->setValue(val))
{
// TODO: Fix bug
// This event happens too early, e.g. when setting config.mode to an invalid value,
// the event is already issued before the error message is given.
rspItemState[QString("/sensors/%1/config/%2").arg(id).arg(pi.key())] = val;
rspItem["success"] = rspItemState;
Event e(RSensors, rid.suffix, id, item);
enqueueEvent(e);
if (item->lastChanged() == item->lastSet())
{
updated = true;
if (rid.suffix == RConfigTholdDark || rid.suffix == RConfigTholdOffset)
{
tholdUpdated = true;
}
else if (rid.suffix == RConfigOffset)
{
offsetUpdated = true;
offset += item->toNumber();
}
else if (rid.suffix == RConfigDelay && sensor->modelId().startsWith(QLatin1String("SML00"))) // Hue motion sensor
{
pendingMask |= R_PENDING_DELAY;
sensor->enableRead(WRITE_DELAY);
sensor->setNextReadTime(WRITE_DELAY, QTime::currentTime());
}
else if (rid.suffix == RConfigDuration && sensor->modelId().startsWith(QLatin1String("FLS-NB")))
{
DBG_Printf(DBG_INFO, "Force read of occupaction delay for sensor %s\n", qPrintable(sensor->address().toStringExt()));
sensor->enableRead(READ_OCCUPANCY_CONFIG);
sensor->setNextReadTime(READ_OCCUPANCY_CONFIG, queryTime.addSecs(1));
queryTime = queryTime.addSecs(1);
Q_Q(DeRestPlugin);
q->startZclAttributeTimer(0);
}
else if (rid.suffix == RConfigLedIndication)
{
pendingMask |= R_PENDING_LEDINDICATION;
sensor->enableRead(WRITE_LEDINDICATION);
sensor->setNextReadTime(WRITE_LEDINDICATION, QTime::currentTime());
}
else if (rid.suffix == RConfigSensitivity)
{
pendingMask |= R_PENDING_SENSITIVITY;
sensor->enableRead(WRITE_SENSITIVITY);
sensor->setNextReadTime(WRITE_SENSITIVITY, QTime::currentTime());
}
else if (rid.suffix == RConfigUsertest)
{
pendingMask |= R_PENDING_USERTEST;
sensor->enableRead(WRITE_USERTEST);
sensor->setNextReadTime(WRITE_USERTEST, QTime::currentTime());
}
}
if (rid.suffix == RConfigMode)
{
if (sensor->modelId().startsWith(QLatin1String("S1")) ||
sensor->modelId().startsWith(QLatin1String("S2")) ||
sensor->modelId().startsWith(QLatin1String("J1")))
{
if (addTaskUbisysConfigureSwitch(task))
{
rspItemState[QString("successfully updated %1").arg(sensor->modelId())] = val;
}
else
{
rspItemState[QString("error %1").arg(sensor->modelId())] = val;
}
rspItem["success"] = rspItemState;
}
else if (sensor->modelId() == QLatin1String("Cable outlet"))
{
QString mode_set = map[pi.key()].toString();
quint64 mode = 10;
if (mode_set == "confort") { mode = 0x00; }
else if (mode_set == "confort-1") { mode = 0x01; }
else if (mode_set == "confort-2") { mode = 0x02; }
else if (mode_set == "eco") { mode = 0x03; }
else if (mode_set == "hors gel") { mode = 0x04; }
else if (mode_set == "off") { mode = 0x05; }
else
{
rspItemState[QString("error unknow mode for %1").arg(sensor->modelId())] = val;
}
if (mode < 10)
{
if (!addTaskControlModeCmd(task, 0x00, mode))
{
rspItemState[QString("error sending command for %1").arg(sensor->modelId())] = val;
}
}
rspItem["success"] = rspItemState;
}
}
if (rid.suffix == RConfigWindowCoveringType)
{
if (sensor->modelId().startsWith(QLatin1String("J1")))
{
bool ok;
int WindowCoveringType = val.toUInt(&ok);
if (ok && addTaskWindowCoveringCalibrate(task, WindowCoveringType))
{
rspItemState[QString("started calibration %1").arg(sensor->modelId())] = val;
}
else
{
rspItemState[QString("error calibration %1").arg(sensor->modelId())] = val;
}
rspItem["success"] = rspItemState;
}
}
if (rid.suffix == RConfigGroup)
{
checkSensorBindingsForClientClusters(sensor);
}
}
else // invalid
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(val.toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (QString(rid.suffix).startsWith("config/ubisys_j1_"))
{
uint16_t mfrCode = VENDOR_UBISYS;
uint16_t attrId;
uint8_t attrType = deCONZ::Zcl16BitUint;
if (rid.suffix == RConfigUbisysJ1Mode)
{
mfrCode = 0x0000;
attrId = 0x0017;
attrType = deCONZ::Zcl8BitBitMap;
}
else if (rid.suffix == RConfigUbisysJ1WindowCoveringType)
{
attrId = 0x0000;
attrType = deCONZ::Zcl8BitEnum;
}
else if (rid.suffix == RConfigUbisysJ1ConfigurationAndStatus)
{
attrId = 0x0007;
attrType = deCONZ::Zcl8BitBitMap;
}
else if (rid.suffix == RConfigUbisysJ1InstalledOpenLimitLift)
{
attrId = 0x0010;
}
else if (rid.suffix == RConfigUbisysJ1InstalledClosedLimitLift)
{
attrId = 0x0011;
}
else if (rid.suffix == RConfigUbisysJ1InstalledOpenLimitTilt)
{
attrId = 0x0012;
}
else if (rid.suffix == RConfigUbisysJ1InstalledClosedLimitTilt)
{
attrId = 0x0013;
}
else if (rid.suffix == RConfigUbisysJ1TurnaroundGuardTime)
{
attrId = 0x1000;
attrType = deCONZ::Zcl8BitUint;
}
else if (rid.suffix == RConfigUbisysJ1LiftToTiltTransitionSteps)
{
attrId = 0x1001;
}
else if (rid.suffix == RConfigUbisysJ1TotalSteps)
{
attrId = 0x1002;
}
else if (rid.suffix == RConfigUbisysJ1LiftToTiltTransitionSteps2)
{
attrId = 0x1003;
}
else if (rid.suffix == RConfigUbisysJ1TotalSteps2)
{
attrId = 0x1004;
}
else if (rid.suffix == RConfigUbisysJ1AdditionalSteps)
{
attrId = 0x1005;
attrType = deCONZ::Zcl8BitUint;
}
else if (rid.suffix == RConfigUbisysJ1InactivePowerThreshold)
{
attrId = 0x1006;
}
else if (rid.suffix == RConfigUbisysJ1StartupSteps)
{
attrId = 0x1007;
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/sensors/%1/%2").arg(id).arg(rid.suffix), QString("unknown attribute")));
rsp.httpStatus = HttpStatusServiceUnavailable;
return REQ_READY_SEND;
}
bool ok;
int attrValue = map[pi.key()].toUInt(&ok);
if (ok && addTaskWindowCoveringSetAttr(task, mfrCode, attrId, attrType, attrValue))
{
rspItemState[QString("set attribute %1").arg(rid.suffix)] = attrValue;