-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathHyperAPI.cpp
1745 lines (1490 loc) · 49.1 KB
/
HyperAPI.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
#ifndef PCH_ENABLED
#include <QResource>
#include <QImage>
#include <QBuffer>
#include <QByteArray>
#include <QTimer>
#include <QList>
#include <QHostAddress>
#include <QMultiMap>
#include <QDir>
#include <QNetworkReply>
#include <chrono>
#include <csignal>
#endif
#include <QCoreApplication>
#include <QHostInfo>
#include <QBuffer>
#include <HyperhdrConfig.h>
#include <api/HyperAPI.h>
#include <leddevice/LedDeviceWrapper.h>
#include <leddevice/LedDevice.h>
#include <leddevice/LedDeviceFactory.h>
#include "../leddevice/dev_net/ProviderRestApi.h"
#include <base/GrabberWrapper.h>
#include <base/SystemWrapper.h>
#include <base/SoundCapture.h>
#include <base/ImageToLedManager.h>
#include <base/AccessManager.h>
#include <flatbufserver/FlatBufferServer.h>
#include <utils/jsonschema/QJsonUtils.h>
#include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/ColorSys.h>
#include <utils/JsonUtils.h>
#include <utils/PerformanceCounters.h>
// bonjour wrapper
#ifdef ENABLE_BONJOUR
#include <bonjour/DiscoveryWrapper.h>
#endif
using namespace hyperhdr;
HyperAPI::HyperAPI(QString peerAddress, Logger* log, bool localConnection, QObject* parent, bool noListener)
: CallbackAPI(log, localConnection, parent)
{
_logsManager = LoggerManager::getInstance();
_noListener = noListener;
_peerAddress = peerAddress;
_streaming_logging_activated = false;
_ledStreamTimer = new QTimer(this);
_colorsStreamingInterval = 50;
_lastSentImage = 0;
connect(_ledStreamTimer, &QTimer::timeout, this, &HyperAPI::handleLedColorsTimer, Qt::UniqueConnection);
Q_INIT_RESOURCE(JSONRPC_schemas);
}
void HyperAPI::handleMessage(const QString& messageString, const QString& httpAuthHeader)
{
try
{
if (HyperHdrInstance::isTerminated())
return;
const QString ident = "JsonRpc@" + _peerAddress;
QJsonObject message;
// parse the message
if (!JsonUtils::parse(ident, messageString, message, _log))
{
sendErrorReply("Errors during message parsing, please consult the HyperHDR Log.");
return;
}
int tan = 0;
if (message.value("tan") != QJsonValue::Undefined)
tan = message["tan"].toInt();
// check basic message
if (!JsonUtils::validate(ident, message, ":schema", _log))
{
sendErrorReply("Errors during message validation, please consult the HyperHDR Log.", "" /*command*/, tan);
return;
}
// check specific message
const QString command = message["command"].toString();
if (!JsonUtils::validate(ident, message, QString(":schema-%1").arg(command), _log))
{
sendErrorReply("Errors during specific message validation, please consult the HyperHDR Log", command, tan);
return;
}
// client auth before everything else but not for http
if (!_noListener && command == "authorize")
{
handleAuthorizeCommand(message, command, tan);
return;
}
// check auth state
if (!BaseAPI::isAuthorized())
{
bool authOk = false;
if (_noListener)
{
QString cToken = httpAuthHeader.mid(5).trimmed();
if (BaseAPI::isTokenAuthorized(cToken))
authOk = true;
}
if (!authOk)
{
sendErrorReply("No Authorization", command, tan);
return;
}
}
bool isRunning = false;
quint8 currentIndex = getCurrentInstanceIndex();
SAFE_CALL_1_RET(_instanceManager.get(), IsInstanceRunning, bool, isRunning, quint8, currentIndex);
if (_hyperhdr == nullptr || !isRunning)
{
sendErrorReply("Not ready", command, tan);
return;
}
else
{
// switch over all possible commands and handle them
if (command == "color")
handleColorCommand(message, command, tan);
else if (command == "image")
handleImageCommand(message, command, tan);
else if (command == "effect")
handleEffectCommand(message, command, tan);
else if (command == "sysinfo")
handleSysInfoCommand(message, command, tan);
else if (command == "serverinfo")
handleServerInfoCommand(message, command, tan);
else if (command == "clear")
handleClearCommand(message, command, tan);
else if (command == "adjustment")
handleAdjustmentCommand(message, command, tan);
else if (command == "sourceselect")
handleSourceSelectCommand(message, command, tan);
else if (command == "config")
handleConfigCommand(message, command, tan);
else if (command == "componentstate")
handleComponentStateCommand(message, command, tan);
else if (command == "ledcolors")
handleLedColorsCommand(message, command, tan);
else if (command == "logging")
handleLoggingCommand(message, command, tan);
else if (command == "processing")
handleProcessingCommand(message, command, tan);
else if (command == "videomodehdr")
handleVideoModeHdrCommand(message, command, tan);
else if (command == "lut-calibration")
handleLutCalibrationCommand(message, command, tan);
else if (command == "instance")
handleInstanceCommand(message, command, tan);
else if (command == "leddevice")
handleLedDeviceCommand(message, command, tan);
else if (command == "save-db")
handleSaveDB(message, command, tan);
else if (command == "load-db")
handleLoadDB(message, command, tan);
else if (command == "tunnel")
handleTunnel(message, command, tan);
else if (command == "signal-calibration")
handleLoadSignalCalibration(message, command, tan);
else if (command == "performance-counters")
handlePerformanceCounters(message, command, tan);
else if (command == "clearall")
handleClearallCommand(message, command, tan);
else if (command == "help")
handleHelpCommand(message, command, tan);
else if (command == "video-crop")
handleCropCommand(message, command, tan);
else if (command == "video-controls")
handleVideoControlsCommand(message, command, tan);
else if (command == "benchmark")
handleBenchmarkCommand(message, command, tan);
else if (command == "lut-install")
handleLutInstallCommand(message, command, tan);
else if (command == "smoothing")
handleSmoothingCommand(message, command, tan);
else if (command == "current-state")
handleCurrentStateCommand(message, command, tan);
// handle not implemented commands
else
handleNotImplemented(command, tan);
}
}
catch (...)
{
sendErrorReply("Exception");
}
}
void HyperAPI::initialize()
{
// init API, REQUIRED!
BaseAPI::init();
// setup auth interface
connect(this, &BaseAPI::SignalPendingTokenClientNotification, this, &HyperAPI::newPendingTokenRequest);
connect(this, &BaseAPI::SignalTokenClientNotification, this, &HyperAPI::handleTokenResponse);
// listen for killed instances
connect(_instanceManager.get(), &HyperHdrManager::SignalInstanceStateChanged, this, &HyperAPI::handleInstanceStateChange);
// pipe callbacks from subscriptions to parent
connect(this, &CallbackAPI::SignalCallbackToClient, this, &HyperAPI::SignalCallbackJsonMessage);
// notify hyperhdr about a jsonMessageForward
if (_hyperhdr != nullptr)
connect(this, &HyperAPI::SignalForwardJsonMessage, _hyperhdr.get(), &HyperHdrInstance::SignalForwardJsonMessage);
}
bool HyperAPI::handleInstanceSwitch(quint8 inst, bool forced)
{
if (BaseAPI::setHyperhdrInstance(inst))
{
Debug(_log, "Client '%s' switch to HyperHDR instance %d", QSTRING_CSTR(_peerAddress), inst);
return true;
}
return false;
}
void HyperAPI::handleColorCommand(const QJsonObject& message, const QString& command, int tan)
{
emit SignalForwardJsonMessage(message);
int priority = message["priority"].toInt();
int duration = message["duration"].toInt(-1);
const QString origin = message["origin"].toString("JsonRpc") + "@" + _peerAddress;
const QJsonArray& jsonColor = message["color"].toArray();
std::vector<uint8_t> colors;
// TODO faster copy
for (auto&& entry : jsonColor)
{
colors.emplace_back(uint8_t(entry.toInt()));
}
BaseAPI::setColor(priority, colors, duration, origin);
sendSuccessReply(command, tan);
}
void HyperAPI::handleImageCommand(const QJsonObject& message, const QString& command, int tan)
{
emit SignalForwardJsonMessage(message);
BaseAPI::ImageCmdData idata;
idata.priority = message["priority"].toInt();
idata.origin = message["origin"].toString("JsonRpc") + "@" + _peerAddress;
idata.duration = message["duration"].toInt(-1);
idata.width = message["imagewidth"].toInt();
idata.height = message["imageheight"].toInt();
idata.scale = message["scale"].toInt(-1);
idata.format = message["format"].toString();
idata.imgName = message["name"].toString("");
idata.data = QByteArray::fromBase64(QByteArray(message["imagedata"].toString().toUtf8()));
QString replyMsg;
if (!BaseAPI::setImage(idata, COMP_IMAGE, replyMsg))
{
sendErrorReply(replyMsg, command, tan);
return;
}
sendSuccessReply(command, tan);
}
void HyperAPI::handleEffectCommand(const QJsonObject& message, const QString& command, int tan)
{
emit SignalForwardJsonMessage(message);
EffectCmdData dat;
dat.priority = message["priority"].toInt();
dat.duration = message["duration"].toInt(-1);
dat.pythonScript = message["pythonScript"].toString();
dat.origin = message["origin"].toString("JsonRpc") + "@" + _peerAddress;
dat.effectName = message["effect"].toObject()["name"].toString();
dat.data = message["imageData"].toString("").toUtf8();
dat.args = message["effect"].toObject()["args"].toObject();
if (BaseAPI::setEffect(dat))
sendSuccessReply(command, tan);
else
sendErrorReply("Effect '" + dat.effectName + "' not found", command, tan);
}
hyperhdr::Components HyperAPI::getActiveComponent()
{
hyperhdr::Components active;
SAFE_CALL_0_RET(_hyperhdr.get(), getCurrentPriorityActiveComponent, hyperhdr::Components, active);
return active;
}
void HyperAPI::handleServerInfoCommand(const QJsonObject& message, const QString& command, int tan)
{
try
{
bool subscribeOnly = false;
if (message.contains("subscribe"))
{
QJsonArray subsArr = message["subscribe"].toArray();
for (const QJsonValueRef entry : subsArr)
{
if (entry == "performance-update" || entry == "lut-calibration-update")
subscribeOnly = true;
}
}
if (!subscribeOnly)
{
QJsonObject info;
/////////////////////
// Instance report //
/////////////////////
BLOCK_CALL_2(_hyperhdr.get(), putJsonInfo, QJsonObject&, info, bool, true);
///////////////////////////
// Available LED devices //
///////////////////////////
QJsonObject ledDevices;
QJsonArray availableLedDevices;
for (auto dev : LedDeviceWrapper::getDeviceMap())
{
availableLedDevices.append(dev.first);
}
ledDevices["available"] = availableLedDevices;
info["ledDevices"] = ledDevices;
///////////////////////
// Sound Device Info //
///////////////////////
#if defined(ENABLE_SOUNDCAPLINUX) || defined(ENABLE_SOUNDCAPWINDOWS) || defined(ENABLE_SOUNDCAPMACOS)
QJsonObject resultSound;
if (_soundCapture != nullptr)
SAFE_CALL_0_RET(_soundCapture.get(), getJsonInfo, QJsonObject, resultSound);
if (!resultSound.isEmpty())
info["sound"] = resultSound;
#endif
/////////////////////////
// System Grabber Info //
/////////////////////////
#if defined(ENABLE_DX) || defined(ENABLE_MAC_SYSTEM) || defined(ENABLE_X11) || defined(ENABLE_FRAMEBUFFER)
QJsonObject resultSGrabber;
if (_systemGrabber != nullptr && _systemGrabber->systemWrapper() != nullptr)
SAFE_CALL_0_RET(_systemGrabber->systemWrapper(), getJsonInfo, QJsonObject, resultSGrabber);
if (!resultSGrabber.isEmpty())
info["systemGrabbers"] = resultSGrabber;
#endif
//////////////////////
// Video grabbers //
//////////////////////
QJsonObject grabbers;
GrabberWrapper* grabberWrapper = (_videoGrabber != nullptr) ? _videoGrabber->grabberWrapper() : nullptr;
#if defined(ENABLE_V4L2) || defined(ENABLE_MF) || defined(ENABLE_AVF)
if (grabberWrapper != nullptr)
SAFE_CALL_0_RET(grabberWrapper, getJsonInfo, QJsonObject, grabbers);
#endif
info["grabbers"] = grabbers;
//////////////////////////////////
// Instances found by Bonjour //
//////////////////////////////////
QJsonArray sessions;
#ifdef ENABLE_BONJOUR
QList<DiscoveryRecord> services;
if (_discoveryWrapper != nullptr)
SAFE_CALL_0_RET(_discoveryWrapper.get(), getAllServices, QList<DiscoveryRecord>, services);
for (const auto& session : services)
{
QJsonObject item;
item["name"] = session.getName();
item["host"] = session.hostName;
item["address"] = session.address;
item["port"] = session.port;
sessions.append(item);
}
info["sessions"] = sessions;
#endif
///////////////////////////
// Instances info //
///////////////////////////
QJsonArray instanceInfo;
for (const auto& entry : BaseAPI::getAllInstanceData())
{
QJsonObject obj;
obj.insert("friendly_name", entry["friendly_name"].toString());
obj.insert("instance", entry["instance"].toInt());
obj.insert("running", entry["running"].toBool());
instanceInfo.append(obj);
}
info["instance"] = instanceInfo;
info["currentInstance"] = getCurrentInstanceIndex();
/////////////////
// MISC //
/////////////////
#if defined(ENABLE_PROTOBUF)
info["hasPROTOBUF"] = 1;
#else
info["hasPROTOBUF"] = 0;
#endif
#if defined(ENABLE_CEC)
info["hasCEC"] = 1;
#else
info["hasCEC"] = 0;
#endif
info["hostname"] = QHostInfo::localHostName();
info["lastError"] = Logger::getLastError();
////////////////
// END //
////////////////
sendSuccessDataReply(QJsonDocument(info), command, tan);
}
else
sendSuccessReply(command, tan);
// AFTER we send the info, the client might want to subscribe to future updates
if (message.contains("subscribe"))
{
// check if listeners are allowed
if (_noListener)
return;
CallbackAPI::subscribe(message["subscribe"].toArray());
}
}
catch (...)
{
sendErrorReply("Exception");
}
}
void HyperAPI::handleClearCommand(const QJsonObject& message, const QString& command, int tan)
{
emit SignalForwardJsonMessage(message);
int priority = message["priority"].toInt();
QString replyMsg;
if (!BaseAPI::clearPriority(priority, replyMsg))
{
sendErrorReply(replyMsg, command, tan);
return;
}
sendSuccessReply(command, tan);
}
void HyperAPI::handleClearallCommand(const QJsonObject& message, const QString& command, int tan)
{
emit SignalForwardJsonMessage(message);
QString replyMsg;
BaseAPI::clearPriority(-1, replyMsg);
sendSuccessReply(command, tan);
}
void HyperAPI::handleHelpCommand(const QJsonObject& message, const QString& command, int tan)
{
QJsonObject req;
req["available_commands"] = "color, image, effect, serverinfo, clear, clearall, adjustment, sourceselect, config, componentstate, ledcolors, logging, processing, sysinfo, videomodehdr, videomode, video-crop, authorize, instance, leddevice, transform, correction, temperature, help";
sendSuccessDataReply(QJsonDocument(req), command, tan);
}
void HyperAPI::handleCropCommand(const QJsonObject& message, const QString& command, int tan)
{
GrabberWrapper* grabberWrapper = (_videoGrabber != nullptr) ? _videoGrabber->grabberWrapper() : nullptr;
const QJsonObject& adjustment = message["crop"].toObject();
int l = adjustment["left"].toInt(0);
int r = adjustment["right"].toInt(0);
int t = adjustment["top"].toInt(0);
int b = adjustment["bottom"].toInt(0);
if (grabberWrapper != nullptr)
emit grabberWrapper->setCropping(l, r, t, b);
sendSuccessReply(command, tan);
}
void HyperAPI::handleBenchmarkCommand(const QJsonObject& message, const QString& command, int tan)
{
GrabberWrapper* grabberWrapper = (_videoGrabber != nullptr) ? _videoGrabber->grabberWrapper() : nullptr;
const QString& subc = message["subcommand"].toString().trimmed();
int status = message["status"].toInt();
if (grabberWrapper != nullptr)
{
if (subc == "ping")
{
emit grabberWrapper->SignalBenchmarkUpdate(status, "pong");
}
else
{
BLOCK_CALL_2(grabberWrapper, benchmarkCapture, int, status, QString, subc);
}
}
sendSuccessReply(command, tan);
}
void HyperAPI::lutDownloaded(QNetworkReply* reply, int hardware_brightness, int hardware_contrast, int hardware_saturation, qint64 time)
{
QString fileName = QDir::cleanPath(_instanceManager->getRootPath() + QDir::separator() + "lut_lin_tables.3d");
QString error = installLut(reply, fileName, hardware_brightness, hardware_contrast, hardware_saturation, time);
if (error == nullptr)
{
Info(_log, "Reloading LUT...");
BaseAPI::setVideoModeHdr(0);
BaseAPI::setVideoModeHdr(1);
QJsonDocument newSet;
SAFE_CALL_1_RET(_hyperhdr.get(), getSetting, QJsonDocument, newSet, settings::type, settings::type::VIDEOGRABBER);
QJsonObject grabber = QJsonObject(newSet.object());
grabber["hardware_brightness"] = hardware_brightness;
grabber["hardware_contrast"] = hardware_contrast;
grabber["hardware_saturation"] = hardware_saturation;
QString newConfig = QJsonDocument(grabber).toJson(QJsonDocument::Compact);
BLOCK_CALL_2(_hyperhdr.get(), setSetting, settings::type, settings::type::VIDEOGRABBER, QString, newConfig);
Info(_log, "New LUT has been installed as: %s (from: %s)", QSTRING_CSTR(fileName), QSTRING_CSTR(reply->url().toString()));
}
else
{
Error(_log, "Error occured while installing new LUT: %s", QSTRING_CSTR(error));
}
QJsonObject report;
report["status"] = (error == nullptr) ? 1 : 0;
report["error"] = error;
sendSuccessDataReply(QJsonDocument(report), "lut-install-update");
}
void HyperAPI::handleLutInstallCommand(const QJsonObject& message, const QString& command, int tan)
{
const QString& address = QString("%1/lut_lin_tables.3d.xz").arg(message["subcommand"].toString().trimmed());
int hardware_brightness = message["hardware_brightness"].toInt(0);
int hardware_contrast = message["hardware_contrast"].toInt(0);
int hardware_saturation = message["hardware_saturation"].toInt(0);
qint64 time = message["now"].toInt(0);
Debug(_log, "Request to install LUT from: %s (params => [%i, %i, %i])", QSTRING_CSTR(address),
hardware_brightness, hardware_contrast, hardware_saturation);
if (_adminAuthorized)
{
QNetworkAccessManager* mgr = new QNetworkAccessManager(this);
connect(mgr, &QNetworkAccessManager::finished, this,
[this, mgr, hardware_brightness, hardware_contrast, hardware_saturation, time](QNetworkReply* reply) {
lutDownloaded(reply, hardware_brightness, hardware_contrast, hardware_saturation, time);
reply->deleteLater();
mgr->deleteLater();
});
QNetworkRequest request(address);
mgr->get(request);
sendSuccessReply(command, tan);
}
else
sendErrorReply("No Authorization", command, tan);
}
void HyperAPI::handleCurrentStateCommand(const QJsonObject& message, const QString& command, int tan)
{
const QString& subc = message["subcommand"].toString().trimmed();
int instance = message["instance"].toInt(0);
if (subc == "average-color")
{
QJsonObject avColor = BaseAPI::getAverageColor(instance);
sendSuccessDataReply(QJsonDocument(avColor), command + "-" + subc, tan);
}
else
handleNotImplemented(command, tan);
}
void HyperAPI::handleSmoothingCommand(const QJsonObject& message, const QString& command, int tan)
{
const QString& subc = message["subcommand"].toString().trimmed().toLower();
int time = message["time"].toInt();
if (subc=="all")
QUEUE_CALL_1(_instanceManager.get(), setSmoothing, int, time)
else
QUEUE_CALL_1(_hyperhdr.get(), setSmoothing, int, time);
sendSuccessReply(command, tan);
}
void HyperAPI::handleVideoControlsCommand(const QJsonObject& message, const QString& command, int tan)
{
#if defined(__APPLE__)
sendErrorReply("Setting video controls is not supported under macOS", command, tan);
return;
#endif
const QJsonObject& adjustment = message["video-controls"].toObject();
int hardware_brightness = adjustment["hardware_brightness"].toInt();
int hardware_contrast = adjustment["hardware_contrast"].toInt();
int hardware_saturation = adjustment["hardware_saturation"].toInt();
int hardware_hue = adjustment["hardware_hue"].toInt();
GrabberWrapper* grabberWrapper = (_videoGrabber != nullptr) ? _videoGrabber->grabberWrapper() : nullptr;
if (grabberWrapper != nullptr)
{
QUEUE_CALL_4(grabberWrapper, setBrightnessContrastSaturationHue, int, hardware_brightness, int, hardware_contrast, int, hardware_saturation, int, hardware_hue);
}
sendSuccessReply(command, tan);
}
void HyperAPI::handleSourceSelectCommand(const QJsonObject& message, const QString& command, int tan)
{
if (message.contains("auto"))
{
BaseAPI::setSourceAutoSelect(message["auto"].toBool(false));
}
else if (message.contains("priority"))
{
BaseAPI::setVisiblePriority(message["priority"].toInt());
}
else
{
sendErrorReply("Priority request is invalid", command, tan);
return;
}
sendSuccessReply(command, tan);
}
void HyperAPI::handleSaveDB(const QJsonObject& message, const QString& command, int tan)
{
if (_adminAuthorized)
{
QJsonObject backup;
SAFE_CALL_0_RET(_instanceManager.get(), getBackup, QJsonObject, backup);
if (!backup.empty())
sendSuccessDataReply(QJsonDocument(backup), command, tan);
else
sendErrorReply("Error while generating the backup file, please consult the HyperHDR logs.", command, tan);
}
else
sendErrorReply("No Authorization", command, tan);
}
void HyperAPI::handleLoadDB(const QJsonObject& message, const QString& command, int tan)
{
if (_adminAuthorized)
{
QString error;
SAFE_CALL_1_RET(_instanceManager.get(), restoreBackup, QString, error, QJsonObject, message);
if (error.isEmpty())
{
#ifdef __linux__
Info(_log, "Exiting now. If HyperHDR is running as a service, systemd should restart the process.");
HyperHdrInstance::signalTerminateTriggered();
QTimer::singleShot(0, _instanceManager.get(), []() {QCoreApplication::exit(1); });
#else
HyperHdrInstance::signalTerminateTriggered();
QTimer::singleShot(0, _instanceManager.get(), []() {QCoreApplication::quit(); });
#endif
}
else
sendErrorReply("Error occured while restoring the backup: " + error, command, tan);
}
else
sendErrorReply("No Authorization", command, tan);
}
void HyperAPI::handlePerformanceCounters(const QJsonObject& message, const QString& command, int tan)
{
QString subcommand = message["subcommand"].toString("");
QString full_command = command + "-" + subcommand;
if (subcommand == "all")
{
QUEUE_CALL_1(_performanceCounters.get(), performanceInfoRequest, bool, true);
sendSuccessReply(command, tan);
}
else if (subcommand == "resources")
{
QUEUE_CALL_1(_performanceCounters.get(), performanceInfoRequest, bool, false);
sendSuccessReply(command, tan);
}
else
sendErrorReply("Unknown subcommand", command, tan);
}
void HyperAPI::handleLoadSignalCalibration(const QJsonObject& message, const QString& command, int tan)
{
QJsonDocument retVal;
QString subcommand = message["subcommand"].toString("");
QString full_command = command + "-" + subcommand;
GrabberWrapper* grabberWrapper = (_videoGrabber != nullptr) ? _videoGrabber->grabberWrapper() : nullptr;
if (grabberWrapper == nullptr)
{
sendErrorReply("No grabbers available", command, tan);
return;
}
if (subcommand == "start")
{
if (_adminAuthorized)
{
SAFE_CALL_0_RET(grabberWrapper, startCalibration, QJsonDocument, retVal);
sendSuccessDataReply(retVal, full_command, tan);
}
else
sendErrorReply("No Authorization", command, tan);
}
else if (subcommand == "stop")
{
SAFE_CALL_0_RET(grabberWrapper, stopCalibration, QJsonDocument, retVal);
sendSuccessDataReply(retVal, full_command, tan);
}
else if (subcommand == "get-info")
{
SAFE_CALL_0_RET(grabberWrapper, getCalibrationInfo, QJsonDocument, retVal);
sendSuccessDataReply(retVal, full_command, tan);
}
else
sendErrorReply("Unknown subcommand", command, tan);
}
void HyperAPI::handleConfigCommand(const QJsonObject& message, const QString& command, int tan)
{
QString subcommand = message["subcommand"].toString("");
QString full_command = command + "-" + subcommand;
if (subcommand == "getschema")
{
handleSchemaGetCommand(message, full_command, tan);
}
else if (subcommand == "setconfig")
{
if (_adminAuthorized)
handleConfigSetCommand(message, full_command, tan);
else
sendErrorReply("No Authorization", command, tan);
}
else if (subcommand == "getconfig")
{
if (_adminAuthorized)
{
QJsonObject getconfig;
BLOCK_CALL_1(_hyperhdr.get(), putJsonConfig, QJsonObject&, getconfig);
sendSuccessDataReply(QJsonDocument(getconfig), full_command, tan);
}
else
sendErrorReply("No Authorization", command, tan);
}
else
{
sendErrorReply("unknown or missing subcommand", full_command, tan);
}
}
void HyperAPI::handleConfigSetCommand(const QJsonObject& message, const QString& command, int tan)
{
if (message.contains("config"))
{
QJsonObject config = message["config"].toObject();
if (BaseAPI::isHyperhdrEnabled())
{
if (BaseAPI::saveSettings(config))
{
sendSuccessReply(command, tan);
}
else
{
sendErrorReply("Save settings failed", command, tan);
}
}
else
sendErrorReply("Saving configuration while HyperHDR is disabled isn't possible", command, tan);
}
}
void HyperAPI::handleSchemaGetCommand(const QJsonObject& message, const QString& command, int tan)
{
// create result
QJsonObject schemaJson, alldevices, properties;
// make sure the resources are loaded (they may be left out after static linking)
Q_INIT_RESOURCE(resource);
// read the hyperhdr json schema from the resource
QString schemaFile = ":/hyperhdr-schema";
try
{
schemaJson = QJsonUtils::readSchema(schemaFile);
}
catch (const std::runtime_error& error)
{
throw std::runtime_error(error.what());
}
// collect all LED Devices
properties = schemaJson["properties"].toObject();
alldevices = LedDeviceWrapper::getLedDeviceSchemas();
properties.insert("alldevices", alldevices);
// collect all available effect schemas
schemaJson.insert("properties", properties);
// send the result
sendSuccessDataReply(QJsonDocument(schemaJson), command, tan);
}
void HyperAPI::handleComponentStateCommand(const QJsonObject& message, const QString& command, int tan)
{
const QJsonObject& componentState = message["componentstate"].toObject();
QString comp = componentState["component"].toString("invalid");
bool compState = componentState["state"].toBool(true);
QString replyMsg;
if (!BaseAPI::setComponentState(comp, compState, replyMsg))
{
sendErrorReply(replyMsg, command, tan);
return;
}
sendSuccessReply(command, tan);
}
void HyperAPI::handleIncomingColors(const std::vector<ColorRgb>& ledValues)
{
_currentLedValues = ledValues;
if (_ledStreamTimer->interval() != _colorsStreamingInterval)
_ledStreamTimer->start(_colorsStreamingInterval);
}
void HyperAPI::handleLedColorsTimer()
{
emit streamLedcolorsUpdate(_currentLedValues);
}
void HyperAPI::handleLedColorsCommand(const QJsonObject& message, const QString& command, int tan)
{
// create result
QString subcommand = message["subcommand"].toString("");
// max 20 Hz (50ms) interval for streaming (default: 10 Hz (100ms))
_colorsStreamingInterval = qMax(message["interval"].toInt(100), 50);
if (subcommand == "ledstream-start")
{
_streaming_leds_reply["success"] = true;
_streaming_leds_reply["command"] = command + "-ledstream-update";
_streaming_leds_reply["tan"] = tan;
subscribeFor("leds-colors");
if (!_ledStreamTimer->isActive() || _ledStreamTimer->interval() != _colorsStreamingInterval)
_ledStreamTimer->start(_colorsStreamingInterval);
QUEUE_CALL_0(_hyperhdr.get(), update);
}
else if (subcommand == "ledstream-stop")
{
subscribeFor("leds-colors", true);
_ledStreamTimer->stop();
}
else if (subcommand == "imagestream-start")
{
if (BaseAPI::isAdminAuthorized())
{
_streaming_image_reply["success"] = true;
_streaming_image_reply["command"] = command + "-imagestream-update";
_streaming_image_reply["tan"] = tan;
subscribeFor("live-video");
}
else
sendErrorReply("No Authorization", command, tan);
}
else if (subcommand == "imagestream-stop")
{
subscribeFor("live-video", true);
}
else
{
return;
}
sendSuccessReply(command + "-" + subcommand, tan);
}
void HyperAPI::handleLoggingCommand(const QJsonObject& message, const QString& command, int tan)
{
// create result
QString subcommand = message["subcommand"].toString("");
if (BaseAPI::isAdminAuthorized())
{
_streaming_logging_reply["success"] = true;
_streaming_logging_reply["command"] = command;
_streaming_logging_reply["tan"] = tan;
if (subcommand == "start")
{
if (!_streaming_logging_activated)
{
_streaming_logging_reply["command"] = command + "-update";
connect(_logsManager.get(), &LoggerManager::newLogMessage, this, &HyperAPI::incommingLogMessage);
Debug(_log, "log streaming activated for client %s", _peerAddress.toStdString().c_str()); // needed to trigger log sending
}
}
else if (subcommand == "stop")
{
if (_streaming_logging_activated)
{
disconnect(_logsManager.get(), &LoggerManager::newLogMessage, this, &HyperAPI::incommingLogMessage);
_streaming_logging_activated = false;
Debug(_log, "log streaming deactivated for client %s", _peerAddress.toStdString().c_str());
}
}
else
{
return;
}
sendSuccessReply(command + "-" + subcommand, tan);
}
else
{
sendErrorReply("No Authorization", command + "-" + subcommand, tan);
}
}
void HyperAPI::handleProcessingCommand(const QJsonObject& message, const QString& command, int tan)
{
BaseAPI::setLedMappingType(ImageToLedManager::mappingTypeToInt(message["mappingType"].toString("multicolor_mean")));
sendSuccessReply(command, tan);
}
void HyperAPI::handleVideoModeHdrCommand(const QJsonObject& message, const QString& command, int tan)
{
if (message.contains("flatbuffers_user_lut_filename"))
{
BaseAPI::setFlatbufferUserLUT(message["flatbuffers_user_lut_filename"].toString(""));
}
BaseAPI::setVideoModeHdr(message["HDR"].toInt());
sendSuccessReply(command, tan);
}
void HyperAPI::handleLutCalibrationCommand(const QJsonObject& message, const QString& command, int tan)
{