forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest_lights.cpp
2210 lines (1954 loc) · 76.2 KB
/
rest_lights.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 "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "json.h"
#include "connectivity.h"
#include "colorspace.h"
/*! Lights REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleLightsApi(const ApiRequest &req, ApiResponse &rsp)
{
if (req.path[2] != QLatin1String("lights"))
{
return REQ_NOT_HANDLED;
}
// GET /api/<apikey>/lights
if ((req.path.size() == 3) && (req.hdr.method() == "GET"))
{
return getAllLights(req, rsp);
}
// POST /api/<apikey>/lights
else if ((req.path.size() == 3) && (req.hdr.method() == "POST"))
{
return searchNewLights(req, rsp);
}
// GET /api/<apikey>/lights/new
else if ((req.path.size() == 4) && (req.hdr.method() == "GET") && (req.path[3] == "new"))
{
return getNewLights(req, rsp);
}
// GET /api/<apikey>/lights/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "GET"))
{
return getLightState(req, rsp);
}
// GET /api/<apikey>/lights/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
else if ((req.path.size() == 5) && (req.hdr.method() == "GET") && (req.path[4] == "data"))
{
return getLightData(req, rsp);
}
// PUT, PATCH /api/<apikey>/lights/<id>/state
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "state"))
{
return setLightState(req, rsp);
}
// PUT, PATCH /api/<apikey>/lights/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH"))
{
return setLightAttributes(req, rsp);
}
// GET /api/<apikey>/lights/<id>/connectivity
if ((req.path.size() == 5) && (req.hdr.method() == "GET") && (req.path[4] == "connectivity"))
{
return getConnectivity(req, rsp, false);
}
// GET /api/<apikey>/lights/<id>/connectivity
if ((req.path.size() == 5) && (req.hdr.method() == "GET") && (req.path[4] == "connectivity2"))
{
return getConnectivity(req, rsp, true);
}
// DELETE /api/<apikey>/lights/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "DELETE"))
{
return deleteLight(req, rsp);
}
// DELETE /api/<apikey>/lights/<id>/scenes
else if ((req.path.size() == 5) && (req.path[4] == "scenes") && (req.hdr.method() == "DELETE"))
{
return removeAllScenes(req, rsp);
}
// DELETE /api/<apikey>/lights/<id>/groups
else if ((req.path.size() == 5) && (req.path[4] == "groups") && (req.hdr.method() == "DELETE"))
{
return removeAllGroups(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! GET /api/<apikey>/lights
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getAllLights(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 (gwLightsEtag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
std::vector<LightNode>::const_iterator i = nodes.begin();
std::vector<LightNode>::const_iterator end = nodes.end();
for (; i != end; ++i)
{
if (i->state() == LightNode::StateDeleted)
{
continue;
}
QVariantMap mnode;
if (lightToMap(req, &*i, mnode))
{
rsp.map[i->id()] = mnode;
}
}
if (rsp.map.isEmpty())
{
rsp.str = "{}"; // return empty object
}
rsp.etag = gwLightsEtag;
return REQ_READY_SEND;
}
/*! POST /api/<apikey>/lights
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::searchNewLights(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
if (!isInNetwork())
{
rsp.list.append(errorToMap(ERR_NOT_CONNECTED, QLatin1String("/lights"), QLatin1String("Not connected")));
rsp.httpStatus = HttpStatusServiceUnavailable;
return REQ_READY_SEND;
}
startSearchLights();
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QLatin1String("/lights")] = QLatin1String("Searching for new devices");
rspItemState[QLatin1String("/lights/duration")] = (double)searchLightsTimeout;
rspItem[QLatin1String("success")] = rspItemState;
rsp.list.append(rspItem);
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/lights/new
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getNewLights(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
if (!searchLightsResult.isEmpty() &&
(searchLightsState == SearchLightsActive || searchLightsState == SearchLightsDone))
{
rsp.map = searchLightsResult;
}
if (searchLightsState == SearchLightsActive)
{
rsp.map["lastscan"] = QLatin1String("active");
}
else if (searchLightsState == SearchLightsDone)
{
rsp.map["lastscan"] = lastLightsScan;
}
else
{
rsp.map["lastscan"] = QLatin1String("none");
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! Put all parameters in a map for later json serialization.
\return true - on success
false - on error
*/
bool DeRestPluginPrivate::lightToMap(const ApiRequest &req, const LightNode *lightNode, QVariantMap &map)
{
Q_UNUSED(req);
if (!lightNode)
{
return false;
}
QVariantMap state;
const ResourceItem *ix = nullptr;
const ResourceItem *iy = nullptr;
for (int i = 0; i < lightNode->itemCount(); i++)
{
const ResourceItem *item = lightNode->itemForIndex(static_cast<size_t>(i));
DBG_Assert(item);
if (!item->isPublic())
{
continue;
}
if (item->descriptor().suffix == RStateOn) { state["on"] = item->toBool(); }
else if (item->descriptor().suffix == RStateBri) { state["bri"] = static_cast<double>(item->toNumber()); }
else if (item->descriptor().suffix == RStateHue) { state["hue"] = static_cast<double>(item->toNumber()); }
else if (item->descriptor().suffix == RStateSat) { state["sat"] = static_cast<double>(item->toNumber()); }
else if (item->descriptor().suffix == RStateCt) { state["ct"] = static_cast<double>(item->toNumber()); }
else if (item->descriptor().suffix == RStateColorMode) { state["colormode"] = item->toString(); }
else if (item->descriptor().suffix == RStateSpeed) { state["speed"] = item->toNumber(); }
else if (item->descriptor().suffix == RStateX) { ix = item; }
else if (item->descriptor().suffix == RStateY) { iy = item; }
else if (item->descriptor().suffix == RStateReachable) { state["reachable"] = item->toBool(); }
else if (item->descriptor().suffix == RConfigCtMin) { map["ctmin"] = item->toNumber(); }
else if (item->descriptor().suffix == RConfigCtMax) { map["ctmax"] = item->toNumber(); }
else if (item->descriptor().suffix == RConfigPowerup) { map["powerup"] = item->toNumber(); }
else if (item->descriptor().suffix == RConfigPowerOnLevel) { map["poweronlevel"] = item->toNumber(); }
else if (item->descriptor().suffix == RConfigPowerOnCt) { map["poweronct"] = item->toNumber(); }
else if (item->descriptor().suffix == RConfigLevelMin) { map["levelmin"] = item->toNumber(); }
else if (item->descriptor().suffix == RConfigId) { map["configid"] = item->toNumber(); }
}
state["alert"] = QLatin1String("none"); // TODO
if (ix && iy)
{
state["effect"] = (lightNode->isColorLoopActive() ? "colorloop" : "none");
QVariantList xy;
double colorX = ix->toNumber();
double colorY = iy->toNumber();
// sanity for colorX
if (colorX > 65279)
{
colorX = 65279;
}
// sanity for colorY
if (colorY > 65279)
{
colorY = 65279;
}
// x = CurrentX / 65536 (CurrentX in the range 0 to 65279 inclusive)
const double x = round(colorX / 6.5535) / 10000.0; // normalize to 0 .. 1
const double y = round(colorY / 6.5535) / 10000.0; // normalize to 0 .. 1
xy.append(x);
xy.append(y);
state["xy"] = xy;
}
map["uniqueid"] = lightNode->uniqueId();
map["name"] = lightNode->name();
map["type"] = lightNode->type();
// Amazon Echo quirks mode
if (req.mode == ApiModeEcho)
{
// OSRAM plug + Ubisys S1/S2
if (lightNode->type().startsWith(QLatin1String("On/Off")))
{
map["modelid"] = QLatin1String("LWB010");
map["manufacturername"] = QLatin1String("Philips");
map["type"] = QLatin1String("Dimmable light");
state["bri"] = (double)254;
}
}
if (req.path.size() > 2 && req.path[2] == QLatin1String("devices"))
{
// don't add in sub device
}
else
{
if (req.mode != ApiModeEcho)
{
map["hascolor"] = lightNode->hasColor();
}
map["modelid"] = lightNode->modelId(); // real model id
map["manufacturername"] = lightNode->manufacturer();
map["swversion"] = lightNode->swBuildId();
QString etag = lightNode->etag;
etag.remove('"'); // no quotes allowed in string
map["etag"] = etag;
}
map["state"] = state;
return true;
}
/*! GET /api/<apikey>/lights/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getLightData(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];
LightNode *lightNode = getLightNodeForId(id);
if (!lightNode || (lightNode->state() != LightNode::StateNormal))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/lights/%1/").arg(id), QString("resource, /lights/%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();
loadLightDataFromDb(lightNode, rsp.list, fromTime, maxRecords);
closeDb();
if (rsp.list.isEmpty())
{
rsp.str = QLatin1String("[]"); // return empty list
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/lights/<id>
\return 0 - on success
-1 - on error
*/
int DeRestPluginPrivate::getLightState(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];
LightNode *lightNode = getLightNodeForId(id);
if (!lightNode || lightNode->state() == LightNode::StateDeleted)
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/lights/%1").arg(id), QString("resource, /lights/%1, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
// handle request to force query light state
if (req.hdr.hasKey("Query-State"))
{
bool enabled = false;
int diff = idleTotalCounter - lightNode->lastRead(READ_ON_OFF);
QString attrs = req.hdr.value("Query-State");
// only read if time since last read is not too short
if (diff > 3)
{
if (attrs.contains("on"))
{
lightNode->enableRead(READ_ON_OFF);
lightNode->setLastRead(READ_ON_OFF, idleTotalCounter);
enabled = true;
}
if (attrs.contains("bri"))
{
lightNode->enableRead(READ_LEVEL);
lightNode->setLastRead(READ_LEVEL, idleTotalCounter);
enabled = true;
}
if (attrs.contains("color") && lightNode->hasColor())
{
lightNode->enableRead(READ_COLOR);
lightNode->setLastRead(READ_COLOR, idleTotalCounter);
enabled = true;
}
}
if (enabled)
{
DBG_Printf(DBG_INFO, "Force read the attributes %s, for node %s\n", qPrintable(attrs), qPrintable(lightNode->address().toStringExt()));
processZclAttributes(lightNode);
}
}
// handle ETag
if (req.hdr.hasKey("If-None-Match"))
{
QString etag = req.hdr.value("If-None-Match");
if (lightNode->etag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
lightToMap(req, lightNode, rsp.map);
rsp.httpStatus = HttpStatusOk;
rsp.etag = lightNode->etag;
return REQ_READY_SEND;
}
/*! Helper to generate a new task with new task and req id based on a reference */
static void copyTaskReq(TaskItem &a, TaskItem &b)
{
b.req.dstAddress() = a.req.dstAddress();
b.req.setDstAddressMode(a.req.dstAddressMode());
b.req.setSrcEndpoint(a.req.srcEndpoint());
b.req.setDstEndpoint(a.req.dstEndpoint());
b.req.setRadius(a.req.radius());
b.req.setTxOptions(a.req.txOptions());
b.req.setSendDelay(a.req.sendDelay());
b.transitionTime = a.transitionTime;
b.onTime = a.onTime;
b.lightNode = a.lightNode;
}
/*! PUT, PATCH /api/<apikey>/lights/<id>/state
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::setLightState(const ApiRequest &req, ApiResponse &rsp)
{
TaskItem taskRef;
QString id = req.path[3];
taskRef.lightNode = getLightNodeForId(id);
uint hue = UINT_MAX;
uint sat = UINT_MAX;
if (req.sock)
{
userActivity();
}
if (!taskRef.lightNode || taskRef.lightNode->state() == LightNode::StateDeleted)
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/lights/%1").arg(id), QString("resource, /lights/%1, not available").arg(id)));
return REQ_READY_SEND;
}
rsp.httpStatus = HttpStatusOk;
if (!taskRef.lightNode->isAvailable())
{
rsp.httpStatus = HttpStatusOk;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/lights/%1").arg(id), QString("resource, /lights/%1, not available").arg(id)));
return REQ_READY_SEND;
}
// set destination parameters
taskRef.req.dstAddress() = taskRef.lightNode->address();
taskRef.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
taskRef.req.setDstEndpoint(taskRef.lightNode->haEndpoint().endpoint());
taskRef.req.setSrcEndpoint(getSrcEndpoint(taskRef.lightNode, taskRef.req));
taskRef.req.setDstAddressMode(deCONZ::ApsExtAddress);
bool ok;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
if (!ok || map.isEmpty())
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/lights/%1/state").arg(id), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
// TODO: check for valid attributes in body
bool isOn = false;
bool hasOn = map.contains("on");
bool hasBri = map.contains("bri");
bool hasHue = map.contains("hue");
bool hasSat = map.contains("sat");
bool hasXy = map.contains("xy");
bool hasCt = map.contains("ct");
bool hasCtInc = map.contains("ct_inc");
bool hasBriInc = map.contains("bri_inc");
bool hasEffect = map.contains("effect");
bool hasEffectColorLoop = false;
bool hasAlert = map.contains("alert");
bool hasWrap = map.contains("wrap");
{
ResourceItem *item = taskRef.lightNode->item(RStateOn);
DBG_Assert(item != nullptr);
isOn = item ? item->toBool() : false;
}
if (taskRef.lightNode->modelId() == QLatin1String("FLS-PP")) // old FLS-PP
{
hasXy = false;
}
// transition time
if (map.contains("transitiontime"))
{
uint tt = map["transitiontime"].toUInt(&ok);
if (ok && tt < 0xFFFFUL)
{
taskRef.transitionTime = tt;
}
}
if (map.contains("ontime"))
{
uint ot = map["ontime"].toUInt(&ok);
if (ok && ot < 0xFFFFUL)
{
taskRef.onTime = ot;
}
}
// FIXME temporary workaround to support window_covering
bool isWindowCoveringDevice = false;
if (taskRef.lightNode->type() == QLatin1String("Window covering device"))
{
isWindowCoveringDevice = true;
}
// on/off
if (hasOn)
{
if (map["on"].type() == QVariant::Bool)
{
isOn = map["on"].toBool();
if (!isOn && taskRef.lightNode->isColorLoopActive())
{
TaskItem task;
copyTaskReq(taskRef, task);
addTaskSetColorLoop(task, false, 15);
taskRef.lightNode->setColorLoopActive(false); // deactivate colorloop if active
}
TaskItem task;
copyTaskReq(taskRef, task);
//FIXME workaround window_convering
if (isWindowCoveringDevice
&& addTaskWindowCovering(task, isOn ? 0x01 /*down*/ : 0x00 /*up*/, 0, 0))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/on").arg(id)] = isOn;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
} // FIXME end workaround window_covering
else if (isOn && taskRef.onTime > 0 && addTaskSetOnOff(task, ONOFF_COMMAND_ON_WITH_TIMED_OFF, taskRef.onTime))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/on").arg(id)] = isOn;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else if (hasBri ||
// map.contains("transitiontime") || // FIXME: use bri if transitionTime is given
addTaskSetOnOff(task, isOn ? ONOFF_COMMAND_ON : ONOFF_COMMAND_OFF, 0)) // onOff task only if no bri or transitionTime is given
{
// GLEDOPTO "W" (1 channel) "GL-C-009" version 1.0.3
// GLEDOPTO "RGB/WW/CW" (5 channel) "GL-C-008" version 1.0.3
// do not honor "with on/off" in a "Move to level (with on/off)" command.
// Workaround by sending ONOFF_COMMAND and a LEVEL_COMMAND:
if (task.lightNode
&& (task.lightNode->modelId() == QLatin1String("GL-C-008") ||
task.lightNode->modelId() == QLatin1String("GL-C-009"))
&& task.lightNode->swBuildId().startsWith(QLatin1String("1.0")))
{
if (hasBri ||
// map.contains("transitiontime") || // FIXME: use bri if transitionTime is given
false)
{
// In case of turning off, the ONOFF_COMMAND should be send after the
// LEVEL_COMMAND (which is far below). Since it pretty works this way,
// it seems not worth the effort to handle the turning-of case separately.
TaskItem task2;
copyTaskReq(taskRef, task2);
addTaskSetOnOff(task2, isOn ? ONOFF_COMMAND_ON : ONOFF_COMMAND_OFF, 0);
}
}
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/on").arg(id)] = isOn;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/lights/%1/state/on").arg(id), QString("invalid value, %1, for parameter, on").arg(map["on"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
// brightness
if (hasBri)
{
uint bri = map["bri"].toUInt(&ok);
if (hasOn && map["on"].type() == QVariant::Bool)
{
if (!isOn)
{
bri = 0; // assume the caller wanted to switch the light off
}
else if (isOn && (bri == 0))
{
bri = 1; // don't turn off light is on is true
}
}
//FIXME workaround window_covering
if (isWindowCoveringDevice)
{
if ((map["bri"].type() == QVariant::String) && map["bri"].toString() == "stop")
{
TaskItem task;
copyTaskReq(taskRef, task);
if (addTaskWindowCovering(task, 0x02 /*stop motion*/, 0, 0))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/groups/%1/action/bri").arg(id)] = map["bri"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else if (ok && (map["bri"].type() == QVariant::Double) && (bri < 256))
{
TaskItem task;
copyTaskReq(taskRef, task);
uint8_t moveToPct = 0x00;
moveToPct = bri * 100 / 254; // Percent 0 - 100 (0x00 - 0x64)
if (taskRef.lightNode->modelId().startsWith(QLatin1String("lumi.curtain")) )
{
moveToPct = 100 - moveToPct;
}
//Legrand invert bri and don't support other value than 0
if (taskRef.lightNode->modelId() == QLatin1String("Shutter switch with neutral"))
{
if (bri == 0)
{
moveToPct = 254;
}
else
{
moveToPct = 0;
}
}
if (addTaskWindowCovering(task, 0x05 /*move to Lift Percent*/, 0, moveToPct))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/bri").arg(id)] = map["bri"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
} // FIXME end workaround window_covering
else if (!isOn && !hasOn)
{
rsp.list.append(errorToMap(ERR_DEVICE_OFF, QString("/lights/%1").arg(id), QString("parameter, /lights/%1/bri, is not modifiable. Device is set to off.").arg(id)));
}
else if ((map["bri"].type() == QVariant::String) && map["bri"].toString() == "stop")
{
TaskItem task;
copyTaskReq(taskRef, task);
if (addTaskStopBrightness(task))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/groups/%1/action/bri").arg(id)] = map["bri"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else if (ok && (map["bri"].type() == QVariant::Double) && (bri < 256))
{
TaskItem task;
copyTaskReq(taskRef, task);
if (addTaskSetBrightness(task, bri, hasOn))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/bri").arg(id)] = map["bri"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/lights/%1/state/bri").arg(id), QString("invalid value, %1, for parameter, bri").arg(map["bri"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
// colorloop
if (hasEffect)
{
QString effect = map["effect"].toString();
if (!isOn)
{
rsp.list.append(errorToMap(ERR_DEVICE_OFF, QString("/lights/%1").arg(id), QString("parameter, /lights/%1/effect, is not modifiable. Device is set to off.").arg(id)));
}
else if ((effect == "none") || (effect == "colorloop"))
{
hasEffectColorLoop = effect == "colorloop";
uint16_t speed = 15;
if (hasEffectColorLoop)
{
if (map.contains("colorloopspeed"))
{
speed = map["colorloopspeed"].toUInt(&ok);
if (ok && (map["colorloopspeed"].type() == QVariant::Double) && (speed < 256) && (speed > 0))
{
// ok
taskRef.lightNode->setColorLoopSpeed(speed);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/lights/%1/state/colorloopspeed").arg(id), QString("invalid value, %1, for parameter, colorloopspeed").arg(map["colorloopspeed"].toString())));
}
}
}
TaskItem task;
copyTaskReq(taskRef, task);
if (addTaskSetColorLoop(task, hasEffectColorLoop, speed))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/effect").arg(id)] = map["effect"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/lights/%1/state/effect").arg(id), QString("invalid value, %1, for parameter, effect").arg(map["effect"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
// hue
if (hasHue)
{
uint hue2 = map["hue"].toUInt(&ok);
if (!isOn)
{
rsp.list.append(errorToMap(ERR_DEVICE_OFF, QString("/lights/%1").arg(id), QString("parameter, /lights/%1/hue, is not modifiable. Device is set to off.").arg(id)));
}
else if (ok && (map["hue"].type() == QVariant::Double) && (hue2 <= MAX_ENHANCED_HUE))
{
hue = hue2;
TaskItem task;
copyTaskReq(taskRef, task);
{ // TODO: this is needed if saturation is set and addTaskSetEnhancedHue() will not be called
task.hueReal = (double)hue / (360.0f * 182.04444f);
if (task.hueReal < 0.0f)
{
task.hueReal = 0.0f;
}
else if (task.hueReal > 1.0f)
{
task.hueReal = 1.0f;
}
task.hue = task.hueReal * 254.0f;
if (hue > MAX_ENHANCED_HUE_Z)
{
hue = MAX_ENHANCED_HUE_Z;
}
task.enhancedHue = hue;
task.taskType = TaskSetEnhancedHue;
}
if (!hasXy && !hasSat)
{
ResourceItem *item = task.lightNode->item(RStateSat);
double r, g, b;
double x, y;
double h = ((360.0 / 65535.0) * hue);
double s = (item ? item->toNumber() : 0) / 255.0;
double v = 1.0;
Hsv2Rgb(&r, &g, &b, h, s, v);
Rgb2xy(&x, &y, r, g, b);
if (x < 0) { x = 0; }
else if (x > 1) { x = 1; }
if (y < 0) { y = 0; }
else if (y > 1) { y = 1; }
DBG_Printf(DBG_INFO, "x: %f, y: %f\n", x, y);
x *= 65535.0;
y *= 65535.0;
if (x > 65279) { x = 65279; }
else if (x < 1) { x = 1; }
if (y > 65279) { y = 65279; }
else if (y < 1) { y = 1; }
item = task.lightNode->item(RStateX);
if (item && item->toNumber() != static_cast<quint16>(x))
{
item->setValue(static_cast<quint16>(x));
Event e(RLights, RStateX, task.lightNode->id(), item);
enqueueEvent(e);
}
item = task.lightNode->item(RStateY);
if (item && item->toNumber() != static_cast<quint16>(y))
{
item->setValue(static_cast<quint16>(y));
Event e(RLights, RStateY, task.lightNode->id(), item);
enqueueEvent(e);
}
}
if (hasSat || // merge later to set hue and saturation
hasXy || hasCt || hasEffectColorLoop ||
addTaskSetEnhancedHue(task, hue)) // will only be evaluated if no sat, xy, ct or colorloop is set
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/hue").arg(id)] = map["hue"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
taskToLocalData(task);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/lights/%1/state/hue").arg(id), QString("invalid value, %1, for parameter, hue").arg(map["hue"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
// saturation
if (hasSat)
{
uint sat2 = map["sat"].toUInt(&ok);
//FIXME workaround window_covering
if (isWindowCoveringDevice)
{
if (ok && (map["sat"].type() == QVariant::Double) && (sat2 < 256))
{
TaskItem task;
copyTaskReq(taskRef, task);
uint8_t moveToPct = 0x00;
moveToPct = sat2 * 100 / 254; // Percent 0 - 100 (0x00 - 0x64)
if (addTaskWindowCovering(task, 0x08 /*move to Tilt Percent*/, 0, moveToPct))
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/lights/%1/state/sat").arg(id)] = map["sat"];
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
}
else
{
rsp.list.append(errorToMap(ERR_INTERNAL_ERROR, QString("/lights/%1").arg(id), QString("Internal error, %1").arg(ERR_BRIDGE_BUSY)));
}
}
} //FIXME workaround window_covering
else if (!isOn)
{
rsp.list.append(errorToMap(ERR_DEVICE_OFF, QString("/lights/%1").arg(id), QString("parameter, /lights/%1/sat, is not modifiable. Device is set to off.").arg(id)));
}
else if (ok && (map["sat"].type() == QVariant::Double) && (sat2 < 256))
{
if (sat2 == 255)
{
sat2 = 254; // max valid value for level attribute
}
TaskItem task;
copyTaskReq(taskRef, task);
sat = sat2;
task.sat = sat;
task.taskType = TaskSetSat;
if (!hasXy && !hasHue)
{
ResourceItem *item = task.lightNode->item(RStateHue);
double r, g, b;
double x, y;
double h = ((360.0 / 65535.0) * (item ? item->toNumber() : 0));
double s = sat / 255.0;
double v = 1.0;