QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
VehicleCameraControl.cc
Go to the documentation of this file.
2
3#include <algorithm>
4
5#include <QtCore/QCryptographicHash>
6#include <QtCore/QDir>
7#include <QtCore/QFileInfo>
8#include <QtCore/QSettings>
9#include <QtNetwork/QNetworkAccessManager>
10#include <QtNetwork/QNetworkReply>
11#include <QtQml/QQmlEngine>
12#include <QtXml/QDomDocument>
13#include <QtXml/QDomNodeList>
14
15#include "AppMessages.h"
16#include "AppSettings.h"
17#include "FTPManager.h"
18#include "LinkInterface.h"
19#include "MAVLinkProtocol.h"
20#include "MissionCommandTree.h"
21#include "QGCCameraIO.h"
22#include "QGCCameraManager.h"
23#include "QGCCompression.h"
24#include "QGCCorePlugin.h"
25#include "QGCFormat.h"
26#include "QGCLoggingCategory.h"
27#include "QGCNetworkHelper.h"
28#include "QGCVideoStreamInfo.h"
29#include "SettingsManager.h"
30#include "Vehicle.h"
31#include "VehicleLinkManager.h"
32#include "VideoManager.h"
33
34QGC_LOGGING_CATEGORY(VehicleCameraControlLog, "Camera.VehicleCameraControl")
35QGC_LOGGING_CATEGORY(VehicleCameraControlVerboseLog, "Camera.VehicleCameraControl.Verbose")
36
37QGCCameraOptionExclusion::QGCCameraOptionExclusion(QObject* parent, QString param_, QString value_, QStringList exclusions_)
38 : QObject(parent)
39 , param(param_)
40 , value(value_)
41 , exclusions(exclusions_)
42{
43}
44
45QGCCameraOptionRange::QGCCameraOptionRange(QObject* parent, QString param_, QString value_, QString targetParam_, QString condition_, QStringList optNames_, QStringList optValues_)
46 : QObject(parent)
47 , param(param_)
48 , value(value_)
49 , targetParam(targetParam_)
50 , condition(condition_)
51 , optNames(optNames_)
52 , optValues(optValues_)
53{
54}
55
56static bool read_attribute(QDomNode& node, const char* tagName, bool& target)
57{
58 QDomNamedNodeMap attrs = node.attributes();
59 if(!attrs.count()) {
60 return false;
61 }
62 QDomNode subNode = attrs.namedItem(tagName);
63 if(subNode.isNull()) {
64 return false;
65 }
66 target = subNode.nodeValue() != "0";
67 return true;
68}
69
70static bool read_attribute(QDomNode& node, const char* tagName, int& target)
71{
72 QDomNamedNodeMap attrs = node.attributes();
73 if(!attrs.count()) {
74 return false;
75 }
76 QDomNode subNode = attrs.namedItem(tagName);
77 if(subNode.isNull()) {
78 return false;
79 }
80 target = subNode.nodeValue().toInt();
81 return true;
82}
83
84static bool read_attribute(QDomNode& node, const char* tagName, QString& target)
85{
86 QDomNamedNodeMap attrs = node.attributes();
87 if(!attrs.count()) {
88 return false;
89 }
90 QDomNode subNode = attrs.namedItem(tagName);
91 if(subNode.isNull()) {
92 return false;
93 }
94 target = subNode.nodeValue();
95 return true;
96}
97
98static bool read_value(QDomNode& element, const char* tagName, QString& target)
99{
100 QDomElement de = element.firstChildElement(tagName);
101 if(de.isNull()) {
102 return false;
103 }
104 target = de.text();
105 return true;
106}
107
108QString VehicleCameraControl::pathSafeNameToken(const QString& name)
109{
110 QString token = name;
111
112 for (QChar& ch : token) {
113 const char16_t c = ch.unicode();
114 const bool safe = ((c >= u'A') && (c <= u'Z')) || ((c >= u'a') && (c <= u'z')) ||
115 ((c >= u'0') && (c <= u'9')) || (c == u'.') || (c == u'-') || (c == u'_');
116 if (!safe) {
117 ch = QLatin1Char('_');
118 }
119 }
120
121 // A leading dot lets a token of only dots act as a relative path element, and Win32
122 // strips trailing dots silently, which would change the name after validation.
123 while (token.startsWith(QLatin1Char('.'))) {
124 token.remove(0, 1);
125 }
126 while (token.endsWith(QLatin1Char('.'))) {
127 token.chop(1);
128 }
129
130 if (token.isEmpty()) {
131 token = QStringLiteral("unknown");
132 }
133
134 return token;
135}
136
137bool VehicleCameraControl::pathIsInside(const QString& baseDirPath, const QString& candidateFilePath)
138{
139 if (baseDirPath.isEmpty() || candidateFilePath.isEmpty()) {
140 return false;
141 }
142
143 // cleanPath() also normalises '\' to '/' on Windows, so this holds on every platform.
144 const QString base = QDir::cleanPath(QDir(baseDirPath).absolutePath());
145 const QString resolved = QDir::cleanPath(QFileInfo(candidateFilePath).absoluteFilePath());
146 return resolved.startsWith(base + QLatin1Char('/'));
147}
148
149QString VehicleCameraControl::cacheFileToken(const QString& vendor, const QString& modelName, int definitionVersion)
150{
151 // pathSafeNameToken() is lossy, so different cameras can reduce to the same readable
152 // prefix. A truncated hash of the original names makes an accidental clash between them
153 // practically impossible. The NUL separator stops "A_B"+"C" and "A"+"B_C" from hashing
154 // the same.
155 const QByteArray rawId = vendor.toUtf8() + '\0' + modelName.toUtf8();
156 const QString idHash =
157 QString::fromLatin1(QCryptographicHash::hash(rawId, QCryptographicHash::Sha256).toHex().left(8));
158
159 return QStringLiteral("%1_%2_%3_%4")
161 .arg(definitionVersion, 3, 10, QLatin1Char('0'));
162}
163
165 : MavlinkCameraControlInterface(vehicle, parent)
166 , _compID(compID)
167{
168 QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
169
170 memcpy(&_mavlinkCameraInfo, info, sizeof(mavlink_camera_information_t));
171
172 // vendor_name, model_name and cam_definition_uri are fixed-size arrays filled straight
173 // from the wire by an unauthenticated peer, with no NUL guarantee. Bound the reads, and
174 // keep the display strings as sent; only the file-name tokens are reduced to a safe
175 // character set.
176 _vendor = QGCMAVLink::boundedStringField(info->vendor_name);
177 _modelName = QGCMAVLink::boundedStringField(info->model_name);
178 const QString definitionUri = QGCMAVLink::boundedStringField(info->cam_definition_uri);
179
180 _cacheFileToken = cacheFileToken(_vendor, _modelName, static_cast<int>(_mavlinkCameraInfo.cam_definition_version));
181
182 const QString cacheDir = SettingsManager::instance()->appSettings()->parameterSavePath();
183 const QString cacheFilePath = QDir(cacheDir).filePath(_cacheFileToken + QStringLiteral(".xml"));
184 if (cacheDir.isEmpty()) {
185 qCWarning(VehicleCameraControlLog) << "Camera definition cache directory is not set";
186 } else if (pathIsInside(cacheDir, cacheFilePath)) {
187 _cacheFile = QDir::cleanPath(cacheFilePath);
188 } else {
189 // Safety net: the cleaned token cannot contain separators, so this only fires if the
190 // path construction changes.
191 qCWarning(VehicleCameraControlLog) << "Refusing camera cache path outside" << cacheDir << ":" << cacheFilePath;
192 }
193
195
196 if (!definitionUri.isEmpty()) {
197 //-- Process camera definition file
198 _handleDefinitionFile(definitionUri);
199 } else {
201 }
202
203 QSettings settings;
204 _photoCaptureMode = static_cast<PhotoCaptureMode>(settings.value(kPhotoMode, static_cast<int>(PHOTO_CAPTURE_SINGLE)).toInt());
205 _photoLapse = settings.value(kPhotoLapse, 1.0).toDouble();
206 _photoLapseCount = settings.value(kPhotoLapseCount, 0).toInt();
207 _thermalOpacity = settings.value(kThermalOpacity, 85.0).toDouble();
208 _thermalMode = static_cast<ThermalViewMode>(settings.value(kThermalMode, static_cast<uint32_t>(THERMAL_BLEND)).toUInt());
209
210 _videoRecordTimeUpdateTimer.setSingleShot(false);
211 _videoRecordTimeUpdateTimer.setInterval(333);
213
214 // Cameras are not required to broadcast CAMERA_SETTINGS when zoom/focus changes,
215 // so re-request it after an accepted zoom/focus command to keep zoom level and
216 // FOV current. The delay also coalesces bursts of zoom/focus commands into a
217 // single request.
218 constexpr int kCameraSettingsRefreshDelayMsecs = 1000;
219 constexpr int kTestCameraSettingsRefreshDelayMsecs = 50;
220 _cameraSettingsRefreshTimer.setSingleShot(true);
221 _cameraSettingsRefreshTimer.setInterval(QGC::runningUnitTests() ? kTestCameraSettingsRefreshDelayMsecs
222 : kCameraSettingsRefreshDelayMsecs);
223 connect(&_cameraSettingsRefreshTimer, &QTimer::timeout, this, [this]() {
224 _cameraSettingsRetries = 0; // Start a fresh request/retry cycle
226 });
227
228 //-- Tracking capabilities
229 _hasTrackingRectCapability = _mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_HAS_TRACKING_RECTANGLE;
230 _hasTrackingPointCapability = _mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_HAS_TRACKING_POINT;
231
232 qCDebug(VehicleCameraControlLog) << "Camera Info:";
233 qCDebug(VehicleCameraControlLog) << " vendor:" << vendor();
234 qCDebug(VehicleCameraControlLog) << " model:" << modelName();
235 qCDebug(VehicleCameraControlLog) << " version:" << version();
236 qCDebug(VehicleCameraControlLog) << " firmware:" << firmwareVersion();
237 qCDebug(VehicleCameraControlLog) << " focal length:" << focalLength();
238 qCDebug(VehicleCameraControlLog) << " sensor size:" << sensorSize();
239 qCDebug(VehicleCameraControlLog) << " resolution:" << resolution();
240 qCDebug(VehicleCameraControlLog) << " captures video:" << capturesVideo();
241 qCDebug(VehicleCameraControlLog) << " captures photos:" << capturesPhotos();
242 qCDebug(VehicleCameraControlLog) << " has modes:" << hasModes();
243 qCDebug(VehicleCameraControlLog) << " has zoom:" << hasZoom();
244 qCDebug(VehicleCameraControlLog) << " has focus:" << hasFocus();
245 qCDebug(VehicleCameraControlLog) << " has tracking:" << hasTracking();
246 qCDebug(VehicleCameraControlLog) << " has video stream:" << hasVideoStream();
247 qCDebug(VehicleCameraControlLog) << " photos in video mode:" << photosInVideoMode();
248 qCDebug(VehicleCameraControlLog) << " video in photo mode:" << videoInPhotoMode();
249}
250
252{
253 // Stop all timers to prevent them from firing during or after destruction
254 _captureStatusTimer.stop();
256 _streamInfoTimer.stop();
257 _streamStatusTimer.stop();
260 _storageInfoTimer.stop();
261
262 delete _netManager;
263 _netManager = nullptr;
264}
265
267{
268 qCDebug(VehicleCameraControlLog) << "_initWhenReady()";
269 if(isBasic()) {
270 qCDebug(VehicleCameraControlLog) << "Basic, MAVLink only messages, no parameters.";
271 //-- Basic cameras have no parameters
272 _paramComplete = true;
273 emit parametersReady();
274 } else {
276 }
277
278 QTimer::singleShot(500, this, &VehicleCameraControl::_requestCameraSettings);
279 connect(&_cameraSettingsTimer, &QTimer::timeout, this, &VehicleCameraControl::_cameraSettingsTimeout);
280
281 QTimer::singleShot(1000, this, &VehicleCameraControl::_checkForVideoStreams);
282
284
285 connect(&_captureStatusTimer, &QTimer::timeout, this, &VehicleCameraControl::_requestCaptureStatus);
286 _captureStatusTimer.setSingleShot(true);
287 _captureStatusTimer.start(1500);
288
289 connect(&_storageInfoTimer, &QTimer::timeout, this, &VehicleCameraControl::_storageInfoTimeout);
290 QTimer::singleShot(2000, this, &VehicleCameraControl::_requestStorageInfo);
291
299
300 emit infoChanged();
301
302 delete _netManager;
303 _netManager = nullptr;
304}
305
307{
308 // Even if the camera itself does not report video capture capability
309 // we can always save locally from a video stream, or use onboard recording
310 // if the camera reports video capture capability.
311 return _mavlinkCameraInfo.flags & (CAMERA_CAP_FLAGS_CAPTURE_VIDEO | CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM);
312}
313
315{
316 // If we have a video stream we can always screen grab from it,
317 //even if the camera itself does not report still capture capability.
318 return _mavlinkCameraInfo.flags & (CAMERA_CAP_FLAGS_CAPTURE_IMAGE | CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM);
319}
320
322{
325 } else if (_photoCaptureStatus() != PHOTO_CAPTURE_IDLE) {
328 // The ui is not set up to support recording video while in photo/survey mode, even if the camera technically supports it.
330 } else if (_mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM || _mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_CAPTURE_VIDEO) {
332 }
333
335}
336
338{
343 } else if (_photoCaptureStatus() == PHOTO_CAPTURE_IDLE) {
344 // We can always do at least a screen grab from the video stream, even if camera doesn't report still capture capability
345 if (_mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM || _mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_CAPTURE_IMAGE) {
347 }
348 }
349
351}
352
354{
355 if (_mavlinkCameraInfo.firmware_version == 0) {
356 return {};
357 }
358 int major = (_mavlinkCameraInfo.firmware_version) & 0xFF;
359 int minor = (_mavlinkCameraInfo.firmware_version >> 8) & 0xFF;
360 int patch = (_mavlinkCameraInfo.firmware_version >> 16) & 0xFF;
361 int dev = (_mavlinkCameraInfo.firmware_version >> 24) & 0xFF;
362 if (dev != 0) {
363 return QString::asprintf("%d.%d.%d.%d", major, minor, patch, dev);
364 }
365 return QString::asprintf("%d.%d.%d", major, minor, patch);
366}
367
369{
370 return QTime(0, 0).addMSecs(static_cast<int>(recordTime())).toString("hh:mm:ss");
371}
372
374{
375 return QGC::bigSizeMBToString(static_cast<quint64>(_storageFree));
376}
377
379{
380 if(_batteryRemaining >= 0) {
381 return QGC::numberToString(static_cast<quint64>(_batteryRemaining)) + " %";
382 }
383 return "";
384}
385
387{
388 if (_resetting) {
389 return;
390 }
391 if (!hasModes()) {
392 qCWarning(VehicleCameraControlLog) << "Camera does not support modes";
393 return;
394 }
395
396 qCDebug(VehicleCameraControlLog) << "Camera set to video mode";
398}
399
401{
402 if (_resetting) {
403 return;
404 }
405 if (!hasModes()) {
406 qCWarning(VehicleCameraControlLog) << "Camera does not support modes";
407 return;
408 }
409
410 qCDebug(VehicleCameraControlLog) << "Camera set to photo mode";
412}
413
415{
416 if (_resetting) {
417 return;
418 }
419 if (!hasModes()) {
420 qCWarning(VehicleCameraControlLog) << "Camera does not support modes";
421 return;
422 }
424 qCWarning(VehicleCameraControlLog) << "Invalid camera mode" << cameraMode;
425 return;
426 }
427 if (_cameraMode == cameraMode) {
428 return;
429 }
430
431 qCDebug(VehicleCameraControlLog) << "Camera mode set to" << cameraModeToStr(cameraMode);
432
433 //-- Does it have a mode parameter?
434 Fact* pMode = mode();
435 if(pMode) {
436 pMode->setRawValue(cameraMode);
438 } else {
439 //-- Use MAVLink Command
440 _vehicle->sendMavCommand(
441 _compID, // Target component
442 MAV_CMD_SET_CAMERA_MODE, // Command id
443 true, // ShowError
444 0, // Reserved (Set to 0)
445 cameraMode); // Camera mode (0: photo, 1: video)
447 }
448}
449
451{
452 if(!_resetting) {
454 QSettings settings;
455 settings.setValue(kPhotoMode, static_cast<int>(mode));
457 }
458}
459
461{
462 _photoLapse = interval;
463 QSettings settings;
464 settings.setValue(kPhotoLapse, interval);
465 emit photoLapseChanged();
466}
467
469{
470 _photoLapseCount = count;
471 QSettings settings;
472 settings.setValue(kPhotoLapseCount, count);
474}
475
477{
478 if(_cameraMode != mode) {
480 emit cameraModeChanged();
481 //-- Update stream status
482 _streamStatusTimer.start(1000);
483 }
484}
485
496
498{
499 if(_resetting) {
500 return false;
501 }
502
504 return stopVideoRecording();
505 } else {
506 return startVideoRecording();
507 }
508
509 return false;
510}
511
513{
514 if (_resetting) {
515 return false;
516 }
518 qCWarning(VehicleCameraControlLog) << "Take photo denied - photo capture is disabled";
519 return false;
520 }
522 qCWarning(VehicleCameraControlLog) << "Take photo denied - already capturing";
523 return false;
524 }
525
526 qCDebug(VehicleCameraControlLog) << "takePhoto()";
527
528 const bool canUseMavlinkImageCapture =
529 (_mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_CAPTURE_IMAGE) &&
531
532 if (canUseMavlinkImageCapture) {
533 const bool timelapse = _photoCaptureMode == PHOTO_CAPTURE_TIMELAPSE;
534 _vehicle->sendMavCommand(
535 _compID,
536 MAV_CMD_IMAGE_START_CAPTURE,
537 true, // ShowError
538 0, // All cameras
539 static_cast<float>(timelapse ? _photoLapse : 0), // Duration between two consecutive pictures (in seconds--ignored if single image)
540 timelapse ? _photoLapseCount : 1); // Number of images to capture total - 0 for unlimited capture
541 // Interval state must be visible immediately so the shutter can stop the sequence before the camera reports status
544 return true;
545 } else {
549 QTimer::singleShot(500, this, [this]() {
551 });
552 return true;
553 } else {
554 QGC::showAppMessage(tr("Timelapse photo capture is not supported on cameras without still capture capability"));
555 }
556 }
557
558 return false;
559}
560
562{
563 if (_resetting) {
564 return false;
565 }
567 qCWarning(VehicleCameraControlLog) << "Stop taking photos requested - not currently capturing multiple photos";
568 return false;
569 }
570
571 qCDebug(VehicleCameraControlLog) << "Camera stop taking photos";
572
573 // Interval capture is only supported directly by cameras
574 _vehicle->sendMavCommand(
575 _compID, // Target component
576 MAV_CMD_IMAGE_STOP_CAPTURE,
577 true, // ShowError
578 0); // All cameras
581
582 return true;
583}
584
586{
587 if (_resetting) {
588 return false;
589 }
591 qCWarning(VehicleCameraControlLog) << "Start video denied - already recording";
592 return false;
593 }
595 qCWarning(VehicleCameraControlLog) << "Start video denied - video capture is disabled";
596 return false;
597 }
598
599 bool useMavlinkCommand = _mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_CAPTURE_VIDEO;
600
601 qCDebug(VehicleCameraControlLog) << "Start video recording:" << (useMavlinkCommand ? "MAVLink command" : "VideoManager");
602
603 if (useMavlinkCommand) {
604 _vehicle->sendMavCommand(
605 _compID, // Target component
606 MAV_CMD_VIDEO_START_CAPTURE,
607 true, // Show error on failure
608 0, // All streams
609 0, // CAMERA_CAPTURE_STATUS streaming frequency
610 0); // All cameras
611 } else {
613 }
614
615 return true;
616}
617
619{
620 if (_resetting) {
621 return false;
622 }
624 qCWarning(VehicleCameraControlLog) << "Stop video recording requested - already idle";
625 return true;
626 }
627
628 bool useMavlinkCommand = _mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_CAPTURE_VIDEO;
629
630 qCDebug(VehicleCameraControlLog) << "Camera stop video recording" << (useMavlinkCommand ? "MAVLink command" : "VideoManager");
631
632 if (useMavlinkCommand) {
633 _vehicle->sendMavCommand(
634 _compID, // Target component
635 MAV_CMD_VIDEO_STOP_CAPTURE,
636 true, // Show error on failure
637 0, // All streams
638 0); // All cameras
639 } else {
641 }
642
643 return true;
644}
645
647{
648 QSettings settings;
649 settings.setValue(kThermalMode, static_cast<uint32_t>(mode));
651 emit thermalModeChanged();
652}
653
655{
656 if(val < 0.0) val = 0.0;
657 if(val > 100.0) val = 100.0;
658 if(fabs(_thermalOpacity - val) > 0.1) {
659 _thermalOpacity = val;
660 QSettings settings;
661 settings.setValue(kThermalOpacity, val);
663 }
664}
665
667{
668 qCDebug(VehicleCameraControlLog) << "Camera set zoom level to" << level;
669 if(hasZoom()) {
670 //-- Limit
671 level = std::min(std::max(level, 0.0), 100.0);
672 if(_vehicle) {
673 _vehicle->sendMavCommand(
674 _compID, // Target component
675 MAV_CMD_SET_CAMERA_ZOOM, // Command id
676 false, // ShowError
677 ZOOM_TYPE_RANGE, // Zoom type
678 static_cast<float>(level)); // Level
679 }
680 }
681}
682
684{
685 qCDebug(VehicleCameraControlLog) << "Camera set focus level to" << level;
686 if(hasFocus()) {
687 //-- Limit
688 level = std::min(std::max(level, 0.0), 100.0);
689 if(_vehicle) {
690 _vehicle->sendMavCommand(
691 _compID, // Target component
692 MAV_CMD_SET_CAMERA_FOCUS, // Command id
693 false, // ShowError
694 FOCUS_TYPE_RANGE, // Focus type
695 static_cast<float>(level)); // Level
696 }
697 }
698}
699
701{
702 if(!_resetting) {
703 qCDebug(VehicleCameraControlLog) << "resetSettings()";
704 _resetting = true;
705 _vehicle->sendMavCommand(
706 _compID, // Target component
707 MAV_CMD_RESET_CAMERA_SETTINGS, // Command id
708 true, // ShowError
709 1); // Do Reset
710 }
711}
712
714{
715 if(!_resetting) {
716 qCDebug(VehicleCameraControlLog) << "formatCard()";
717 if(_vehicle) {
718 _vehicle->sendMavCommand(
719 _compID, // Target component
720 MAV_CMD_STORAGE_FORMAT, // Command id
721 true, // ShowError
722 id, // Storage ID (1 for first, 2 for second, etc.)
723 1); // Do Format
724 }
725 }
726}
727
729{
730 qCDebug(VehicleCameraControlLog) << "Camera step zoom" << direction;
731 if(_vehicle && hasZoom()) {
732 _vehicle->sendMavCommand(
733 _compID, // Target component
734 MAV_CMD_SET_CAMERA_ZOOM, // Command id
735 false, // ShowError
736 ZOOM_TYPE_STEP, // Zoom type
737 direction); // Direction (-1 wide, 1 tele)
738 }
739}
740
742{
743 qCDebug(VehicleCameraControlLog) << "Camera start zoom" << direction;
744 if(_vehicle && hasZoom()) {
745 _vehicle->sendMavCommand(
746 _compID, // Target component
747 MAV_CMD_SET_CAMERA_ZOOM, // Command id
748 false, // ShowError
749 ZOOM_TYPE_CONTINUOUS, // Zoom type
750 direction); // Direction (-1 wide, 1 tele)
751 }
752}
753
755{
756 qCDebug(VehicleCameraControlLog) << "Camera stop zoom";
757 if(_vehicle && hasZoom()) {
758 _vehicle->sendMavCommand(
759 _compID, // Target component
760 MAV_CMD_SET_CAMERA_ZOOM, // Command id
761 false, // ShowError
762 ZOOM_TYPE_CONTINUOUS, // Zoom type
763 0); // Direction (-1 wide, 1 tele)
764 }
765}
766
768{
769 qCDebug(VehicleCameraControlLog) << "Camera step focus" << direction;
770 if(_vehicle && hasFocus()) {
771 _vehicle->sendMavCommand(
772 _compID, // Target component
773 MAV_CMD_SET_CAMERA_FOCUS, // Command id
774 false, // ShowError
775 FOCUS_TYPE_STEP, // Focus type
776 direction); // Direction (-1 in, 1 out)
777 }
778}
779
781{
782 qCDebug(VehicleCameraControlLog) << "Camera start focus" << direction;
783 if(_vehicle && hasFocus()) {
784 _vehicle->sendMavCommand(
785 _compID, // Target component
786 MAV_CMD_SET_CAMERA_FOCUS, // Command id
787 false, // ShowError
788 FOCUS_TYPE_CONTINUOUS, // Focus type
789 direction); // Direction (-1 in, 1 out)
790 }
791}
792
794{
795 qCDebug(VehicleCameraControlLog) << "Camera stop focus";
796 if(_vehicle && hasFocus()) {
797 _vehicle->sendMavCommand(
798 _compID, // Target component
799 MAV_CMD_SET_CAMERA_FOCUS, // Command id
800 false, // ShowError
801 FOCUS_TYPE_CONTINUOUS, // Focus type
802 0); // Direction (-1 in, 1 out)
803 }
804}
805
807{
808 qCDebug(VehicleCameraControlLog) << "Camera request capture status - retries:" << _cameraCaptureStatusRetries;
809
810 if(_cameraCaptureStatusRetries++ % 2 == 0) {
811 qCDebug(VehicleCameraControlLog) << " Sending REQUEST_MESSAGE:MAVLINK_MSG_ID_CAMERA_CAPTURE_STATUS";
812 _vehicle->sendMavCommand(
813 _compID, // target component
814 MAV_CMD_REQUEST_MESSAGE, // command id
815 false, // showError
816 MAVLINK_MSG_ID_CAMERA_CAPTURE_STATUS); // msgid
817 } else {
818 qCDebug(VehicleCameraControlLog) << " Sending MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS (legacy)";
819 _vehicle->sendMavCommand(
820 _compID, // target component
821 MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS, // command id
822 false, // showError
823 1); // Do Request
824 }
825}
826
828{
829 _updateActiveList();
830 _updateRanges(pFact);
831}
832
833void VehicleCameraControl::_mavCommandResult(quint32 vehicleId, int component, int command, int result, int failureCode)
834{
835 Q_UNUSED(failureCode);
836
837 //-- Is this ours?
838 if (_vehicle->id() != vehicleId || compID() != component) {
839 return;
840 }
841 if (_streamCommandPending && (result != MAV_RESULT_IN_PROGRESS) &&
842 ((command == MAV_CMD_VIDEO_START_STREAMING) || (command == MAV_CMD_VIDEO_STOP_STREAMING))) {
843 //-- Answered, or given up on: the next stream to stop or start can be
844 _streamCommandPending = false;
845 _syncStreams();
846 }
847 if (result == MAV_RESULT_IN_PROGRESS) {
848 //-- Do Nothing
849 qCDebug(VehicleCameraControlLog) << "In progress response for" << command;
850 } else if(result == MAV_RESULT_ACCEPTED) {
851 switch(command) {
852 case MAV_CMD_RESET_CAMERA_SETTINGS:
853 _resetting = false;
854 if(isBasic()) {
856 } else {
857 QTimer::singleShot(500, this, &VehicleCameraControl::_requestAllParameters);
858 QTimer::singleShot(2500, this, &VehicleCameraControl::_requestCameraSettings);
859 }
860 break;
861 case MAV_CMD_VIDEO_START_CAPTURE:
863 _captureStatusTimer.start(1000);
864 break;
865 case MAV_CMD_VIDEO_STOP_CAPTURE:
867 _captureStatusTimer.start(1000);
868 break;
869 case MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS:
871 break;
872 case MAV_CMD_REQUEST_STORAGE_INFORMATION:
874 break;
875 case MAV_CMD_IMAGE_START_CAPTURE:
876 _captureStatusTimer.start(1000);
877 break;
878 case MAV_CMD_SET_CAMERA_ZOOM:
879 case MAV_CMD_SET_CAMERA_FOCUS:
881 break;
882 }
883 } else {
884 QString commandStr = MissionCommandTree::instance()->rawName(static_cast<MAV_CMD>(command));
885 if ((result == MAV_RESULT_TEMPORARILY_REJECTED) || (result == MAV_RESULT_FAILED)) {
886 if (result == MAV_RESULT_TEMPORARILY_REJECTED) {
887 qCDebug(VehicleCameraControlLog) << "Command temporarily rejected (MAV_RESULT_TEMPORARILY_REJECTED) for" << commandStr;
888 } else {
889 qCDebug(VehicleCameraControlLog) << "Command failed (MAV_RESULT_FAILED) for" << commandStr;
890 }
891 switch(command) {
892 case MAV_CMD_RESET_CAMERA_SETTINGS:
893 _resetting = false;
894 qCDebug(VehicleCameraControlLog) << "Failed to reset camera settings";
895 break;
896 case MAV_CMD_IMAGE_START_CAPTURE:
897 case MAV_CMD_IMAGE_STOP_CAPTURE:
898 if(++_captureInfoRetries <= 5) {
899 _captureStatusTimer.start(1000);
900 } else {
901 qCDebug(VehicleCameraControlLog) << "Giving up start/stop image capture";
903 }
904 break;
905 case MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS:
906 if(++_cameraCaptureStatusRetries <= 5) {
907 _captureStatusTimer.start(1000);
908 } else {
909 qCDebug(VehicleCameraControlLog) << "Giving up requesting capture status";
910 }
911 break;
912 case MAV_CMD_REQUEST_STORAGE_INFORMATION:
913 if(++_storageInfoRetries <= 5) {
914 QTimer::singleShot(1000, this, &VehicleCameraControl::_requestStorageInfo);
915 } else {
916 qCDebug(VehicleCameraControlLog) << "Giving up requesting storage status";
917 }
918 break;
919 }
920 } else {
921 qCDebug(VehicleCameraControlLog) << "Bad response for" << commandStr << QGCMAVLink::mavResultToString(result);
922 }
923 }
924}
925
927{
928 if(_videoCaptureStatusValue != captureStatus) {
929 _videoCaptureStatusValue = captureStatus;
931 if(captureStatus == VIDEO_CAPTURE_STATUS_RUNNING) {
932 _recordTime = 0;
933 _recTime = QTime::currentTime();
935 } else {
937 _recordTime = 0;
938 emit recordTimeChanged();
939 }
940 }
941}
942
944{
945 _recordTime = static_cast<uint32_t>(_recTime.msecsTo(QTime::currentTime()));
946 emit recordTimeChanged();
947}
948
950{
951 // Only track time here when not using MAVLink video capture (to avoid double-tracking)
953 return;
954 }
955
956 if (recording) {
957 _recordTime = 0;
958 _recTime = QTime::currentTime();
960 } else {
962 _recordTime = 0;
963 emit recordTimeChanged();
964 }
965}
966
968{
969 if(_photoCaptureStatusValue != captureStatus) {
970 qCDebug(VehicleCameraControlLog) << "Set Photo Status:" << captureStatus;
971 _photoCaptureStatusValue = captureStatus;
973 }
974}
975
976bool VehicleCameraControl::_loadCameraDefinitionFile(QByteArray& bytes)
977{
978 QByteArray originalData(bytes);
979 //-- Handle localization
980 if(!_handleLocalization(bytes)) {
981 return false;
982 }
983
984 QDomDocument doc;
985 const QDomDocument::ParseResult result = doc.setContent(bytes, QDomDocument::ParseOption::Default);
986 if (!result) {
987 qCCritical(VehicleCameraControlLog) << "Unable to parse camera definition file on line:" << result.errorLine;
988 qCCritical(VehicleCameraControlLog) << result.errorMessage;
989 return false;
990 }
991 //-- Load camera constants
992 QDomNodeList defElements = doc.elementsByTagName(kDefnition);
993 if(!defElements.size() || !_loadConstants(defElements)) {
994 qCWarning(VehicleCameraControlLog) << "Unable to load camera constants from camera definition";
995 return false;
996 }
997 //-- Load camera parameters
998 QDomNodeList paramElements = doc.elementsByTagName(kParameters);
999 if(!paramElements.size()) {
1000 qCDebug(VehicleCameraControlLog) << "No parameters to load from camera";
1001 return false;
1002 }
1003 if(!_loadSettings(paramElements)) {
1004 qCWarning(VehicleCameraControlLog) << "Unable to load camera parameters from camera definition";
1005 return false;
1006 }
1007 //-- If this is new, cache it
1008 if(!_cached) {
1009 qCDebug(VehicleCameraControlLog) << "Saving camera definition file" << _cacheFile;
1010 QFile file(_cacheFile);
1011 if (!file.open(QIODevice::WriteOnly)) {
1012 qWarning() << QString("Could not save cache file %1. Error: %2").arg(_cacheFile).arg(file.errorString());
1013 } else {
1014 file.write(originalData);
1015 }
1016 }
1017 return true;
1018}
1019
1020bool VehicleCameraControl::_loadConstants(const QDomNodeList nodeList)
1021{
1022 QDomNode node = nodeList.item(0);
1023 if(!read_attribute(node, kVersion, _version)) {
1024 return false;
1025 }
1026 if(!read_value(node, kModel, _modelName)) {
1027 return false;
1028 }
1029 if(!read_value(node, kVendor, _vendor)) {
1030 return false;
1031 }
1032 return true;
1033}
1034
1035bool VehicleCameraControl::_loadSettings(const QDomNodeList nodeList)
1036{
1037 QDomNode node = nodeList.item(0);
1038 QDomElement elem = node.toElement();
1039 QDomNodeList parameters = elem.elementsByTagName(kParameter);
1040 //-- Pre-process settings (maintain order and skip non-controls)
1041 for(int i = 0; i < parameters.size(); i++) {
1042 QDomNode parameterNode = parameters.item(i);
1043 QString name;
1044 if(read_attribute(parameterNode, kName, name)) {
1045 bool control = true;
1046 read_attribute(parameterNode, kControl, control);
1047 if(control) {
1048 _settings << name;
1049 }
1050 } else {
1051 qCritical() << "Parameter entry missing parameter name";
1052 return false;
1053 }
1054 }
1055 //-- Load parameters
1056 for(int i = 0; i < parameters.size(); i++) {
1057 QDomNode parameterNode = parameters.item(i);
1058 QString factName;
1059 read_attribute(parameterNode, kName, factName);
1060 QString type;
1061 if(!read_attribute(parameterNode, kType, type)) {
1062 qCritical() << QString("Parameter %1 missing parameter type").arg(factName);
1063 return false;
1064 }
1065 //-- Does it have a control?
1066 bool control = true;
1067 read_attribute(parameterNode, kControl, control);
1068 //-- Is it read only?
1069 bool readOnly = false;
1070 read_attribute(parameterNode, kReadOnly, readOnly);
1071 //-- Is it write only?
1072 bool writeOnly = false;
1073 read_attribute(parameterNode, kWriteOnly, writeOnly);
1074 //-- It can't be both
1075 if(readOnly && writeOnly) {
1076 qCritical() << QString("Parameter %1 cannot be both read only and write only").arg(factName);
1077 }
1078 //-- Param type
1079 bool unknownType;
1080 FactMetaData::ValueType_t factType = FactMetaData::stringToType(type, unknownType);
1081 if (unknownType) {
1082 qCritical() << QString("Unknown type for parameter %1").arg(factName);
1083 return false;
1084 }
1085 //-- By definition, custom types do not have control
1086 if(factType == FactMetaData::valueTypeCustom) {
1087 control = false;
1088 }
1089 //-- Description
1090 QString description;
1091 if(!read_value(parameterNode, kDescription, description)) {
1092 qCritical() << QString("Parameter %1 missing parameter description").arg(factName);
1093 return false;
1094 }
1095 //-- Check for updates
1096 QStringList updates = _loadUpdates(parameterNode);
1097 if(updates.size()) {
1098 qCDebug(VehicleCameraControlVerboseLog) << "Parameter" << factName << "requires updates for:" << updates;
1099 _requestUpdates[factName] = updates;
1100 }
1101 //-- Build metadata
1102 FactMetaData* metaData = new FactMetaData(factType, factName, this);
1103 QQmlEngine::setObjectOwnership(metaData, QQmlEngine::CppOwnership);
1104 metaData->setShortDescription(description);
1105 metaData->setLongDescription(description);
1106 metaData->setHasControl(control);
1107 metaData->setReadOnly(readOnly);
1108 metaData->setWriteOnly(writeOnly);
1109 //-- Options (enums)
1110 QDomElement optionElem = parameterNode.toElement();
1111 QDomNodeList optionsRoot = optionElem.elementsByTagName(kOptions);
1112 if(optionsRoot.size()) {
1113 //-- Iterate options
1114 QDomNode optionsNode = optionsRoot.item(0);
1115 QDomElement optionsElem = optionsNode.toElement();
1116 QDomNodeList options = optionsElem.elementsByTagName(kOption);
1117 for(int optionIndex = 0; optionIndex < options.size(); optionIndex++) {
1118 QDomNode option = options.item(optionIndex);
1119 QString optName;
1120 QString optValue;
1121 QVariant optVariant;
1122 if(!_loadNameValue(option, factName, metaData, optName, optValue, optVariant)) {
1123 delete metaData;
1124 return false;
1125 }
1126 metaData->addEnumInfo(optName, optVariant);
1127 _originalOptNames[factName] << optName;
1128 _originalOptValues[factName] << optVariant;
1129 //-- Check for exclusions
1130 QStringList exclusions = _loadExclusions(option);
1131 if(exclusions.size()) {
1132 qCDebug(VehicleCameraControlVerboseLog) << "New exclusions:" << factName << optValue << exclusions;
1133 QGCCameraOptionExclusion* pExc = new QGCCameraOptionExclusion(this, factName, optValue, exclusions);
1134 QQmlEngine::setObjectOwnership(pExc, QQmlEngine::CppOwnership);
1135 _valueExclusions.append(pExc);
1136 }
1137 //-- Check for range rules
1138 if(!_loadRanges(option, factName, optValue)) {
1139 delete metaData;
1140 return false;
1141 }
1142 }
1143 }
1144 QString defaultValue;
1145 if(read_attribute(parameterNode, kDefault, defaultValue)) {
1146 QVariant defaultVariant;
1147 QString errorString;
1148 if (metaData->convertAndValidateRaw(defaultValue, false, defaultVariant, errorString)) {
1149 metaData->setRawDefaultValue(defaultVariant);
1150 } else {
1151 qWarning() << "Invalid default value for" << factName
1152 << " type:" << metaData->type()
1153 << " value:" << defaultValue
1154 << " error:" << errorString;
1155 }
1156 }
1157 //-- Set metadata and Fact
1158 if (_nameToFactMetaDataMap.contains(factName)) {
1159 qWarning() << QStringLiteral("Duplicate fact name:") << factName;
1160 delete metaData;
1161 } else {
1162 {
1163 //-- Check for Min Value
1164 QString attr;
1165 if(read_attribute(parameterNode, kMin, attr)) {
1166 QVariant typedValue;
1167 QString errorString;
1168 if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) {
1169 metaData->setRawMin(typedValue);
1170 } else {
1171 qWarning() << "Invalid min value for" << factName
1172 << " type:" << metaData->type()
1173 << " value:" << attr
1174 << " error:" << errorString;
1175 }
1176 }
1177 }
1178 {
1179 //-- Check for Max Value
1180 QString attr;
1181 if(read_attribute(parameterNode, kMax, attr)) {
1182 QVariant typedValue;
1183 QString errorString;
1184 if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) {
1185 metaData->setRawMax(typedValue);
1186 } else {
1187 qWarning() << "Invalid max value for" << factName
1188 << " type:" << metaData->type()
1189 << " value:" << attr
1190 << " error:" << errorString;
1191 }
1192 }
1193 }
1194 {
1195 //-- Check for Step Value
1196 QString attr;
1197 if(read_attribute(parameterNode, kStep, attr)) {
1198 QVariant typedValue;
1199 QString errorString;
1200 if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) {
1201 metaData->setRawIncrement(typedValue.toDouble());
1202 } else {
1203 qWarning() << "Invalid step value for" << factName
1204 << " type:" << metaData->type()
1205 << " value:" << attr
1206 << " error:" << errorString;
1207 }
1208 }
1209 }
1210 {
1211 //-- Check for Decimal Places
1212 QString attr;
1213 if(read_attribute(parameterNode, kDecimalPlaces, attr)) {
1214 QVariant typedValue;
1215 QString errorString;
1216 if (metaData->convertAndValidateRaw(attr, true /* convertOnly */, typedValue, errorString)) {
1217 metaData->setDecimalPlaces(typedValue.toInt());
1218 } else {
1219 qWarning() << "Invalid decimal places value for" << factName
1220 << " type:" << metaData->type()
1221 << " value:" << attr
1222 << " error:" << errorString;
1223 }
1224 }
1225 }
1226 {
1227 //-- Check for Units
1228 QString attr;
1229 if(read_attribute(parameterNode, kUnit, attr)) {
1230 metaData->setRawUnits(attr);
1231 }
1232 }
1233 qCDebug(VehicleCameraControlLog) << "New parameter:" << factName << (readOnly ? "ReadOnly" : "Writable") << (writeOnly ? "WriteOnly" : "Readable");
1234 _nameToFactMetaDataMap[factName] = metaData;
1235 Fact* pFact = new Fact(_compID, factName, factType, this);
1236 QQmlEngine::setObjectOwnership(pFact, QQmlEngine::CppOwnership);
1237 pFact->setMetaData(metaData);
1238 pFact->containerSetRawValue(metaData->rawDefaultValue());
1239 QGCCameraParamIO* pIO = new QGCCameraParamIO(this, pFact, _vehicle);
1240 QQmlEngine::setObjectOwnership(pIO, QQmlEngine::CppOwnership);
1241 _paramIO[factName] = pIO;
1242 _addFact(pFact, factName);
1243 }
1244 }
1245 if(_nameToFactMetaDataMap.size() > 0) {
1246 _addFactGroup(this, "camera");
1247 _processRanges();
1249 emit activeSettingsChanged();
1250 return true;
1251 }
1252 return false;
1253}
1254
1255bool VehicleCameraControl::_handleLocalization(QByteArray& bytes)
1256{
1257 QDomDocument doc;
1258 const QDomDocument::ParseResult result = doc.setContent(bytes, QDomDocument::ParseOption::Default);
1259 if (!result) {
1260 qCritical() << "Unable to parse camera definition file on line:" << result.errorLine;
1261 qCritical() << result.errorMessage;
1262 return false;
1263 }
1264 //-- Find out where we are
1265 QLocale locale = QLocale::system();
1266#if defined (Q_OS_MACOS)
1267 locale = QLocale(locale.name());
1268#endif
1269 QString localeName = locale.name().toLower().replace("-", "_");
1270 qCDebug(VehicleCameraControlLog) << "Current locale:" << localeName;
1271 if(localeName == "en_us") {
1272 // Nothing to do
1273 return true;
1274 }
1275 QDomNodeList locRoot = doc.elementsByTagName(kLocalization);
1276 if(!locRoot.size()) {
1277 // Nothing to do
1278 return true;
1279 }
1280 //-- Iterate locales
1281 QDomNode node = locRoot.item(0);
1282 QDomElement elem = node.toElement();
1283 QDomNodeList locales = elem.elementsByTagName(kLocale);
1284 for(int i = 0; i < locales.size(); i++) {
1285 QDomNode localeNode = locales.item(i);
1286 QString name;
1287 if(!read_attribute(localeNode, kName, name)) {
1288 qWarning() << "Localization entry is missing its name attribute";
1289 continue;
1290 }
1291 // If we found a direct match, deal with it now
1292 if(localeName == name.toLower().replace("-", "_")) {
1293 return _replaceLocaleStrings(localeNode, bytes);
1294 }
1295 }
1296 //-- No direct match. Pick first matching language (if any)
1297 localeName = localeName.left(3);
1298 for(int i = 0; i < locales.size(); i++) {
1299 QDomNode localeNode = locales.item(i);
1300 QString name;
1301 read_attribute(localeNode, kName, name);
1302 if(name.toLower().startsWith(localeName)) {
1303 return _replaceLocaleStrings(localeNode, bytes);
1304 }
1305 }
1306 //-- Could not find a language to use
1307 qWarning() << "No match for" << QLocale::system().name() << "in camera definition file";
1308 //-- Just use default, en_US
1309 return true;
1310}
1311
1312bool VehicleCameraControl::_replaceLocaleStrings(const QDomNode node, QByteArray& bytes)
1313{
1314 QDomElement stringElem = node.toElement();
1315 QDomNodeList strings = stringElem.elementsByTagName(kStrings);
1316 for(int i = 0; i < strings.size(); i++) {
1317 QDomNode stringNode = strings.item(i);
1318 QString original;
1319 QString translated;
1320 if(read_attribute(stringNode, kOriginal, original)) {
1321 if(read_attribute(stringNode, kTranslated, translated)) {
1322 QString o; o = "\"" + original + "\"";
1323 QString t; t = "\"" + translated + "\"";
1324 bytes.replace(o.toUtf8(), t.toUtf8());
1325 o = ">" + original + "<";
1326 t = ">" + translated + "<";
1327 bytes.replace(o.toUtf8(), t.toUtf8());
1328 }
1329 }
1330 }
1331 return true;
1332}
1333
1335{
1336 //-- Reset receive list
1337 for(const QString& paramName: _paramIO.keys()) {
1338 if(_paramIO[paramName]) {
1339 _paramIO[paramName]->setParamRequest();
1340 } else {
1341 qCritical() << "QGCParamIO is NULL" << paramName;
1342 }
1343 }
1344 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
1345 if (sharedLink) {
1347 mavlink_msg_param_ext_request_list_pack_chan(
1348 MAVLinkProtocol::instance()->getSystemId(), static_cast<uint8_t>(MAVLinkProtocol::getComponentId()),
1349 sharedLink->mavlinkChannel(), &msg, _vehicle->id(), static_cast<uint8_t>(compID()));
1350 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg);
1351 }
1352 qCDebug(VehicleCameraControlVerboseLog) << "Request all parameters";
1353}
1354
1355QString VehicleCameraControl::_getParamName(const char* param_id)
1356{
1357 // This will null terminate the name string
1358 char parameterNameWithNull[MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN + 1] = {};
1359 (void) strncpy(parameterNameWithNull, param_id, MAVLINK_MSG_PARAM_VALUE_FIELD_PARAM_ID_LEN);
1360 const QString parameterName(parameterNameWithNull);
1361 return parameterName;
1362}
1363
1365{
1366 QString paramName = _getParamName(paramExtAck.param_id);
1367 qCDebug(VehicleCameraControlLog).noquote() << "Received PARAM_EXT_ACK:"
1368 << "\n\tParam name:" << paramName
1369 << "\n\tResult:" << static_cast<int>(paramExtAck.param_result)
1370 << "\n\tType:" << static_cast<int>(paramExtAck.param_type);
1371
1372 if(!_paramIO.contains(paramName)) {
1373 qCWarning(VehicleCameraControlLog) << "Received PARAM_EXT_ACK for unknown param:" << paramName;
1374 return;
1375 }
1376 if(_paramIO[paramName]) {
1377 _paramIO[paramName]->handleParamAck(paramExtAck);
1378 } else {
1379 qCritical() << "QGCParamIO is NULL" << paramName;
1380 }
1381}
1382
1384{
1385 QString paramName = _getParamName(paramExtValue.param_id);
1386 qCDebug(VehicleCameraControlLog).noquote() << "Received PARAM_EXT_VALUE:"
1387 << "\n\tParam name:" << paramName
1388 << "\n\tType:" << static_cast<int>(paramExtValue.param_type)
1389 << "\n\tIndex:" << static_cast<int>(paramExtValue.param_index)
1390 << "\n\tCount:" << static_cast<int>(paramExtValue.param_count);
1391
1392 if(!_paramIO.contains(paramName)) {
1393 qCWarning(VehicleCameraControlLog) << "Received PARAM_EXT_VALUE for unknown param:" << paramName;
1394 return;
1395 }
1396 if(_paramIO[paramName]) {
1397 _paramIO[paramName]->handleParamValue(paramExtValue);
1398 } else {
1399 qCritical() << "QGCParamIO is NULL" << paramName;
1400 }
1401}
1402
1403void VehicleCameraControl::_updateActiveList()
1404{
1405 //-- Clear out excluded parameters based on exclusion rules
1406 QStringList exclusionList;
1408 Fact* pFact = getFact(param->param);
1409 if(pFact) {
1410 QString option = pFact->rawValueString();
1411 if(param->value == option) {
1412 exclusionList << param->exclusions;
1413 }
1414 }
1415 }
1416 QStringList active;
1417 for(QString key: _settings) {
1418 if(!exclusionList.contains(key)) {
1419 active.append(key);
1420 }
1421 }
1422 if(active != _activeSettings) {
1423 qCDebug(VehicleCameraControlVerboseLog) << "Excluding" << exclusionList;
1424 _activeSettings = active;
1425 emit activeSettingsChanged();
1426 //-- Force validity of "Facts" based on active set
1427 if(_paramComplete) {
1428 emit parametersReady();
1429 }
1430 }
1431}
1432
1433bool VehicleCameraControl::_processConditionTest(const QString conditionTest)
1434{
1435 enum {
1436 TEST_NONE,
1437 TEST_EQUAL,
1438 TEST_NOT_EQUAL,
1439 TEST_GREATER,
1440 TEST_SMALLER
1441 };
1442 qCDebug(VehicleCameraControlVerboseLog) << "_processConditionTest(" << conditionTest << ")";
1443 int op = TEST_NONE;
1444 QStringList test;
1445
1446 auto split = [&conditionTest](const QString& sep ) {
1447 return conditionTest.split(sep, Qt::SkipEmptyParts);
1448 };
1449
1450 if(conditionTest.contains("!=")) {
1451 test = split("!=");
1452 op = TEST_NOT_EQUAL;
1453 } else if(conditionTest.contains("=")) {
1454 test = split("=");
1455 op = TEST_EQUAL;
1456 } else if(conditionTest.contains(">")) {
1457 test = split(">");
1458 op = TEST_GREATER;
1459 } else if(conditionTest.contains("<")) {
1460 test = split("<");
1461 op = TEST_SMALLER;
1462 }
1463 if(test.size() == 2) {
1464 Fact* pFact = getFact(test[0]);
1465 if(pFact) {
1466 switch(op) {
1467 case TEST_EQUAL:
1468 return pFact->rawValueString() == test[1];
1469 case TEST_NOT_EQUAL:
1470 return pFact->rawValueString() != test[1];
1471 case TEST_GREATER:
1472 return pFact->rawValueString() > test[1];
1473 case TEST_SMALLER:
1474 return pFact->rawValueString() < test[1];
1475 case TEST_NONE:
1476 break;
1477 }
1478 } else {
1479 qWarning() << "Invalid condition parameter:" << test[0] << "in" << conditionTest;
1480 return false;
1481 }
1482 }
1483 qWarning() << "Invalid condition" << conditionTest;
1484 return false;
1485}
1486
1487bool VehicleCameraControl::_processCondition(const QString condition)
1488{
1489 qCDebug(VehicleCameraControlVerboseLog) << "_processCondition(" << condition << ")";
1490 bool result = true;
1491 bool andOp = true;
1492 if(!condition.isEmpty()) {
1493 QStringList scond = condition.split(" ", Qt::SkipEmptyParts);
1494 while(scond.size()) {
1495 QString test = scond.first();
1496 scond.removeFirst();
1497 if(andOp) {
1498 result = result && _processConditionTest(test);
1499 } else {
1500 result = result || _processConditionTest(test);
1501 }
1502 if(!scond.size()) {
1503 return result;
1504 }
1505 andOp = scond.first().toUpper() == "AND";
1506 scond.removeFirst();
1507 }
1508 }
1509 return result;
1510}
1511
1512void VehicleCameraControl::_updateRanges(Fact* pFact)
1513{
1514 QMap<Fact*, QGCCameraOptionRange*> rangesSet;
1515 QMap<Fact*, QString> rangesReset;
1516 QStringList changedList;
1517 QStringList resetList;
1518 QStringList updates;
1519 //-- Iterate range sets looking for limited ranges
1520 for(QGCCameraOptionRange* pRange: _optionRanges) {
1521 //-- If this fact or one of its conditions is part of this range set
1522 if(!changedList.contains(pRange->targetParam) && (pRange->param == pFact->name() || pRange->condition.contains(pFact->name()))) {
1523 Fact* pRFact = getFact(pRange->param); //-- This parameter
1524 Fact* pTFact = getFact(pRange->targetParam); //-- The target parameter (the one its range is to change)
1525 if(pRFact && pTFact) {
1526 //qCDebug(VehicleCameraControlVerboseLog) << "Check new set of options for" << pTFact->name();
1527 QString option = pRFact->rawValueString(); //-- This parameter value
1528 //-- If this value (and condition) triggers a change in the target range
1529 //qCDebug(VehicleCameraControlVerboseLog) << "Range value:" << pRange->value << "Current value:" << option << "Condition:" << pRange->condition;
1530 if(pRange->value == option && _processCondition(pRange->condition)) {
1531 if(pTFact->enumStrings() != pRange->optNames) {
1532 //-- Set limited range set
1533 rangesSet[pTFact] = pRange;
1534 }
1535 changedList << pRange->targetParam;
1536 }
1537 }
1538 }
1539 }
1540 //-- Iterate range sets again looking for resets
1541 for(QGCCameraOptionRange* pRange: _optionRanges) {
1542 if(!changedList.contains(pRange->targetParam) && (pRange->param == pFact->name() || pRange->condition.contains(pFact->name()))) {
1543 Fact* pTFact = getFact(pRange->targetParam); //-- The target parameter (the one its range is to change)
1544 if(!resetList.contains(pRange->targetParam)) {
1545 if(pTFact->enumStrings() != _originalOptNames[pRange->targetParam]) {
1546 //-- Restore full option set
1547 rangesReset[pTFact] = pRange->targetParam;
1548 }
1549 resetList << pRange->targetParam;
1550 }
1551 }
1552 }
1553 //-- Update limited range set
1554 for (Fact* f: rangesSet.keys()) {
1555 f->setEnumInfo(rangesSet[f]->optNames, rangesSet[f]->optVariants);
1556 if(!updates.contains(f->name())) {
1557 emit f->enumsChanged();
1558 qCDebug(VehicleCameraControlVerboseLog) << "Limited set of options for:" << f->name() << rangesSet[f]->optNames;;
1559 updates << f->name();
1560 }
1561 }
1562 //-- Restore full range set
1563 for (Fact* f: rangesReset.keys()) {
1564 f->setEnumInfo(_originalOptNames[rangesReset[f]], _originalOptValues[rangesReset[f]]);
1565 if(!updates.contains(f->name())) {
1566 emit f->enumsChanged();
1567 qCDebug(VehicleCameraControlVerboseLog) << "Restore full set of options for:" << f->name() << _originalOptNames[f->name()];
1568 updates << f->name();
1569 }
1570 }
1571 //-- Parameter update requests
1572 if(_requestUpdates.contains(pFact->name())) {
1573 for(const QString& param: _requestUpdates[pFact->name()]) {
1574 if(!_updatesToRequest.contains(param)) {
1575 _updatesToRequest << param;
1576 }
1577 }
1578 }
1579 if(_updatesToRequest.size()) {
1580 QTimer::singleShot(500, this, &VehicleCameraControl::_requestParamUpdates);
1581 }
1582}
1583
1585{
1586 for(const QString& param: _updatesToRequest) {
1587 _paramIO[param]->paramRequest();
1588 }
1589 _updatesToRequest.clear();
1590}
1591
1593{
1594 qCDebug(VehicleCameraControlLog) << "_requestCameraSettings() - retries:" << _cameraSettingsRetries << "timer active:" << _cameraSettingsTimer.isActive();
1595 if(_vehicle) {
1596 // Use REQUEST_MESSAGE instead of deprecated REQUEST_CAMERA_SETTINGS
1597 // first time and every other time after that.
1598
1599 if(_cameraSettingsRetries % 2 == 0) {
1600 qCDebug(VehicleCameraControlLog) << " Sending REQUEST_MESSAGE:MAVLINK_MSG_ID_CAMERA_SETTINGS";
1601 _vehicle->sendMavCommand(
1602 _compID, // target component
1603 MAV_CMD_REQUEST_MESSAGE, // command id
1604 false, // showError
1605 MAVLINK_MSG_ID_CAMERA_SETTINGS); // msgid
1606 } else {
1607 qCDebug(VehicleCameraControlLog) << " Sending MAV_CMD_REQUEST_CAMERA_SETTINGS (legacy)";
1608 _vehicle->sendMavCommand(
1609 _compID, // Target component
1610 MAV_CMD_REQUEST_CAMERA_SETTINGS, // command id
1611 false, // showError
1612 1); // Do Request
1613 }
1614 if(_cameraSettingsTimer.isActive()) {
1615 qCDebug(VehicleCameraControlLog) << "_requestCameraSettings() - RESTARTING already active timer";
1616 } else {
1617 qCDebug(VehicleCameraControlLog) << "_requestCameraSettings() - starting timer";
1618 }
1619 _cameraSettingsTimer.start(1000); // Wait up to a second for it
1620 }
1621
1622}
1623
1625{
1626 qCDebug(VehicleCameraControlLog) << "_requestStorageInfo() - retries:" << _storageInfoRetries << "timer active:" << _storageInfoTimer.isActive();
1627 if(_vehicle) {
1628 // Use REQUEST_MESSAGE instead of deprecated REQUEST_STORAGE_INFORMATION
1629 // first time and every other time after that.
1630 if(_storageInfoRetries % 2 == 0) {
1631 qCDebug(VehicleCameraControlLog) << " Sending REQUEST_MESSAGE:MAVLINK_MSG_ID_STORAGE_INFORMATION";
1632 _vehicle->sendMavCommand(
1633 _compID, // target component
1634 MAV_CMD_REQUEST_MESSAGE, // command id
1635 false, // showError
1636 MAVLINK_MSG_ID_STORAGE_INFORMATION, // msgid
1637 0); // storage ID
1638 } else {
1639 qCDebug(VehicleCameraControlLog) << " Sending MAV_CMD_REQUEST_STORAGE_INFORMATION (legacy)";
1640 _vehicle->sendMavCommand(
1641 _compID, // Target component
1642 MAV_CMD_REQUEST_STORAGE_INFORMATION, // command id
1643 false, // showError
1644 0, // Storage ID (0 for all, 1 for first, 2 for second, etc.)
1645 1); // Do Request
1646 }
1647 qCDebug(VehicleCameraControlLog) << "_requestStorageInfo() - starting timer";
1648 _storageInfoTimer.start(1000); // Wait up to a second for it
1649 }
1650}
1651
1653{
1654 qCDebug(VehicleCameraControlLog).noquote() << "Received CAMERA_SETTINGS - stopping timer, resetting retries:"
1655 << "\n\tMode:" << settings.mode_id
1656 << "\n\tZoom level:" << settings.zoomLevel
1657 << "\n\tFocus level:" << settings.focusLevel;
1658
1659 _cameraSettingsTimer.stop();
1661
1662 _setCameraMode(static_cast<CameraMode>(settings.mode_id));
1663 qreal z = static_cast<qreal>(settings.zoomLevel);
1664 qreal f = static_cast<qreal>(settings.focusLevel);
1665 if(std::isfinite(z) && z != _zoomLevel) {
1666 _zoomLevel = z;
1667 emit zoomLevelChanged();
1668 }
1669 if(std::isfinite(f) && f != _focusLevel) {
1670 _focusLevel = f;
1671 emit focusLevelChanged();
1672 }
1673}
1674
1676{
1677 qCDebug(VehicleCameraControlLog) << "Received STORAGE_INFORMATION - stopping timer, resetting retries:"
1678 << "\n\tStorage id:" << storageInformation.storage_id
1679 << "\n\tStorage count:" << storageInformation.storage_count
1680 << "\n\tStatus:"<< storageStatusToStr(storageInformation.status)
1681 << "\n\tTotal capacity:" << storageInformation.total_capacity
1682 << "\n\tUsed capacity:" << storageInformation.used_capacity
1683 << "\n\tAvailable capacity:" << storageInformation.available_capacity;
1684
1685 _storageInfoTimer.stop();
1687
1688 if(storageInformation.status == STORAGE_STATUS_READY) {
1689 uint32_t t = static_cast<uint32_t>(storageInformation.total_capacity);
1690 if(_storageTotal != t) {
1691 _storageTotal = t;
1692 emit storageTotalChanged();
1693 }
1694 uint32_t a = static_cast<uint32_t>(storageInformation.available_capacity);
1695 if(_storageFree != a) {
1696 _storageFree = a;
1697 emit storageFreeChanged();
1698 }
1699 }
1700 if(_storageStatus != static_cast<StorageStatus>(storageInformation.status)) {
1701 _storageStatus = static_cast<StorageStatus>(storageInformation.status);
1702 emit storageStatusChanged();
1703 }
1704}
1705
1707{
1708 qCDebug(VehicleCameraControlLog).noquote() << "Received BATTERY_STATUS:"
1709 << "\n\tBattery remaining (%):" << bs.battery_remaining;
1710
1711 if(bs.battery_remaining >= 0 && _batteryRemaining != static_cast<int>(bs.battery_remaining)) {
1712 _batteryRemaining = static_cast<int>(bs.battery_remaining);
1714 }
1715}
1716
1718{
1719 qCDebug(VehicleCameraControlLog).noquote() << "Received CAMERA_CAPTURE_STATUS - stopping timer, resetting retries:"
1720 << "\n\tImage status:" << captureImageStatusToStr(cameraCaptureStatus.image_status)
1721 << "\n\tVideo status:" << captureVideoStatusToStr(cameraCaptureStatus.video_status)
1722 << "\n\tInterval:" << cameraCaptureStatus.image_interval
1723 << "\n\tRecording time (ms):" << cameraCaptureStatus.recording_time_ms
1724 << "\n\tCapacity:" << cameraCaptureStatus.available_capacity;
1725
1726 _captureStatusTimer.stop();
1728
1729 //-- Disk Free Space
1730 uint32_t a = static_cast<uint32_t>(cameraCaptureStatus.available_capacity);
1731 if(_storageFree != a) {
1732 _storageFree = a;
1733 emit storageFreeChanged();
1734 }
1735 //-- Do we have recording time?
1736 if(cameraCaptureStatus.recording_time_ms) {
1737 // Resync our _recTime timer to the time info received from the camera component
1738 _recordTime = cameraCaptureStatus.recording_time_ms;
1739 _recTime = _recTime.addMSecs(_recTime.msecsTo(QTime::currentTime()) - static_cast<int>(cameraCaptureStatus.recording_time_ms));
1740 emit recordTimeChanged();
1741 }
1742 //-- Video/Image Capture Status
1743 uint8_t vs = cameraCaptureStatus.video_status < static_cast<uint8_t>(VIDEO_CAPTURE_STATUS_LAST) ? cameraCaptureStatus.video_status : static_cast<uint8_t>(VIDEO_CAPTURE_STATUS_UNDEFINED);
1744 uint8_t ps = cameraCaptureStatus.image_status < static_cast<uint8_t>(PHOTO_CAPTURE_LAST) ? cameraCaptureStatus.image_status : static_cast<uint8_t>(PHOTO_CAPTURE_STATUS_UNDEFINED);
1747 //-- Keep asking for it once in a while when recording
1749 _captureStatusTimer.start(5000);
1750 //-- Same while a single image capture is busy
1752 _captureStatusTimer.start(1000);
1753 //-- Interval capture can run for hours; poll at the video cadence
1755 _captureStatusTimer.start(5000);
1756 }
1757}
1758
1760{
1761 qCDebug(VehicleCameraControlLog).noquote() << "Received VIDEO_STREAM_INFORMATION:"
1762 << "\n\tStream ID:" << videoStreamInformation.stream_id
1763 << "\n\tStream count:" << videoStreamInformation.count
1764 << "\n\tType:" << static_cast<int>(videoStreamInformation.type)
1765 << "\n\tFlags:" << Qt::hex << Qt::showbase << videoStreamInformation.flags << Qt::dec << Qt::noshowbase
1766 << "\n\tBitrate (bits/s):" << videoStreamInformation.bitrate
1767 << "\n\tFramerate (fps):" << videoStreamInformation.framerate
1768 << "\n\tResolution:" << videoStreamInformation.resolution_h << "x" << videoStreamInformation.resolution_v
1769 << "\n\tRotation (deg):" << videoStreamInformation.rotation
1770 << "\n\tHFOV (deg):" << videoStreamInformation.hfov
1771 << "\n\tURI:" << videoStreamInformation.uri;
1772
1773 _expectedCount = videoStreamInformation.count;
1774 if(!_findStream(videoStreamInformation.stream_id, false)) {
1775 qCDebug(VehicleCameraControlLog) << "Create stream handler for stream ID:" << videoStreamInformation.stream_id;
1776 QGCVideoStreamInfo* pStream = new QGCVideoStreamInfo(videoStreamInformation, this);
1777 QQmlEngine::setObjectOwnership(pStream, QQmlEngine::CppOwnership);
1778 _streams.append(pStream);
1779 //-- Thermal is handled separately and not listed
1780 if(!pStream->isThermal()) {
1781 _streamLabels.append(pStream->name());
1782 if (_streamLabels.size() == 1) {
1783 //-- The camera's first stream is the current one, which it transmits without being asked
1784 _transmittedStreams.insert(pStream->streamID());
1785 }
1786 emit streamsChanged();
1787 emit streamLabelsChanged();
1788 } else {
1789 emit thermalStreamChanged();
1790 }
1791 }
1792 //-- Check for missing count
1793 if(_streams.count() < _expectedCount) {
1794 _streamInfoTimer.start(1000);
1795 } else if (_streamInfoTimer.isActive()) {
1796 //-- Done
1797 qCDebug(VehicleCameraControlLog) << "All stream handlers done";
1798 _streamInfoTimer.stop();
1800 emit autoStreamChanged();
1801 emit _vehicle->cameraManager()->streamChanged();
1802 }
1803}
1804
1806{
1807 qCDebug(VehicleCameraControlLog) << "Received VIDEO_STREAM_STATUS - stopping timer, resetting retries:"
1808 << "\n\tStream ID:" << videoStreamStatus.stream_id
1809 << "\n\tFlags:" << Qt::hex << Qt::showbase << videoStreamStatus.flags << Qt::dec << Qt::noshowbase
1810 << "\n\tBitrate (bits/s):" << videoStreamStatus.bitrate
1811 << "\n\tFramerate (fps):" << videoStreamStatus.framerate
1812 << "\n\tResolution: " << videoStreamStatus.resolution_h << "x" << videoStreamStatus.resolution_v
1813 << "\n\tRotation (deg):" << videoStreamStatus.rotation
1814 << "\n\tHFOV (deg):" << videoStreamStatus.hfov;
1815
1816 _streamStatusTimer.stop();
1818
1819 QGCVideoStreamInfo* pInfo = _findStream(videoStreamStatus.stream_id);
1820 if(pInfo) {
1821 pInfo->update(videoStreamStatus);
1822 }
1823}
1824
1826{
1827 qCDebug(VehicleCameraControlLog).noquote() << "Received CAMERA_TRACKING_IMAGE_STATUS:"
1828 << "\n\tTracking status:" << static_cast<int>(trackingImageStatus.tracking_status)
1829 << "\n\tTracking mode:" << static_cast<int>(trackingImageStatus.tracking_mode)
1830 << "\n\tPoint:" << trackingImageStatus.point_x << "," << trackingImageStatus.point_y
1831 << "\n\tRectangle:" << trackingImageStatus.rec_top_x << "," << trackingImageStatus.rec_top_y
1832 << " -> " << trackingImageStatus.rec_bottom_x << "," << trackingImageStatus.rec_bottom_y
1833 << "\n\tRadius:" << trackingImageStatus.radius;
1834
1835 _trackingImageStatus = trackingImageStatus;
1836
1837 const bool active = ((_trackingImageStatus.tracking_status & CAMERA_TRACKING_STATUS_FLAGS_ACTIVE) != 0) && trackingEnabled();
1838 const bool isPoint = active && (_trackingImageStatus.tracking_mode == CAMERA_TRACKING_MODE_POINT);
1839
1840 if (!active) {
1841 qCDebug(VehicleCameraControlLog) << "Tracking off";
1842 _trackingImageRect = {};
1845 } else if (isPoint) {
1846 const QPointF point(std::clamp(static_cast<qreal>(_trackingImageStatus.point_x), 0.0, 1.0),
1847 std::clamp(static_cast<qreal>(_trackingImageStatus.point_y), 0.0, 1.0));
1848 qreal radius = static_cast<qreal>(_trackingImageStatus.radius);
1849 if (qIsNaN(radius) || radius <= 0) {
1850 radius = 0.05;
1851 } else {
1852 radius = std::clamp(radius, 0.0, 1.0);
1853 }
1854 qCDebug(VehicleCameraControlLog) << "Tracking Point [" << point << "] radius:" << radius;
1855 _trackingImageRect = {};
1856 if (_trackingImagePoint != point) {
1857 _trackingImagePoint = point;
1859 }
1860 if (!qFuzzyCompare(_trackingImageRadius, radius)) {
1861 _trackingImageRadius = radius;
1863 }
1864 } else {
1865 // Rectangle tracking
1866 const QRectF rect = QRectF(QPointF(std::clamp(static_cast<qreal>(_trackingImageStatus.rec_top_x), 0.0, 1.0),
1867 std::clamp(static_cast<qreal>(_trackingImageStatus.rec_top_y), 0.0, 1.0)),
1868 QPointF(std::clamp(static_cast<qreal>(_trackingImageStatus.rec_bottom_x), 0.0, 1.0),
1869 std::clamp(static_cast<qreal>(_trackingImageStatus.rec_bottom_y), 0.0, 1.0))).normalized();
1870 qCDebug(VehicleCameraControlLog) << "Tracking Rect [" << rect << "]";
1873 if (_trackingImageRect != rect) {
1874 _trackingImageRect = rect;
1876 }
1877 }
1878
1879 if (_trackingImageIsActive != active) {
1880 _trackingImageIsActive = active;
1882 }
1883 if (_trackingImageIsPoint != isPoint) {
1884 _trackingImageIsPoint = isPoint;
1886 }
1887}
1888
1890{
1891 if (stream != _currentStream && stream >= 0 && stream < _streamLabels.count()) {
1892 _currentStream = stream;
1893 emit currentStreamChanged();
1894 //-- Whoever displays the streams names the extra ones here, before the camera is told which to stop and start
1895 emit _vehicle->cameraManager()->streamChanged();
1896 _syncStreams();
1898 if(pInfo) {
1899 //-- Update stream status
1900 _requestStreamStatus(static_cast<uint8_t>(pInfo->streamID()));
1901 }
1902 }
1903}
1904
1905void VehicleCameraControl::setExtraStreams(const QList<quint8>& streamIds)
1906{
1907 if (streamIds != _extraStreams) {
1908 _extraStreams = streamIds;
1909 _syncStreams();
1910 }
1911}
1912
1913void VehicleCameraControl::_syncStreams()
1914{
1916 //-- Its answer brings this back
1917 return;
1918 }
1919 QList<quint8> wanted = _extraStreams;
1920 QGCVideoStreamInfo* pInfo = currentStreamInstance();
1921 if (pInfo && !_currentStreamStopped && !wanted.contains(pInfo->streamID())) {
1922 wanted.append(pInfo->streamID());
1923 }
1924 //-- Stops first: a camera may not transmit more streams than it is left with
1925 QList<quint8> stopped = _transmittedStreams.values();
1926 std::sort(stopped.begin(), stopped.end());
1927 for (const quint8 streamID : std::as_const(stopped)) {
1928 if (!wanted.contains(streamID)) {
1929 _transmittedStreams.remove(streamID);
1930 _sendStreamCommand(MAV_CMD_VIDEO_STOP_STREAMING, streamID);
1931 return;
1932 }
1933 }
1934 for (const quint8 streamID : std::as_const(wanted)) {
1935 if (!_transmittedStreams.contains(streamID)) {
1936 _transmittedStreams.insert(streamID);
1937 _sendStreamCommand(MAV_CMD_VIDEO_START_STREAMING, streamID);
1938 return;
1939 }
1940 }
1941}
1942
1943void VehicleCameraControl::_sendStreamCommand(MAV_CMD command, quint8 streamID)
1944{
1945 qCDebug(VehicleCameraControlLog) << ((command == MAV_CMD_VIDEO_START_STREAMING) ? "Starting stream:"
1946 : "Stopping stream:")
1947 << streamID;
1948 //-- Set first: a command that can't be sent is answered from within the call
1949 _streamCommandPending = true;
1950 _vehicle->sendMavCommand(_compID, // Target component
1951 command, // Command id
1952 false, // ShowError
1953 streamID); // Stream ID
1954}
1955
1957{
1959 //-- Stop current stream, whether or not the camera is taken to transmit it
1960 _transmittedStreams.insert(pInfo->streamID());
1961 }
1962 _currentStreamStopped = true;
1963 _syncStreams();
1964}
1965
1967{
1969 //-- Start current stream, whether or not the camera is taken to transmit it
1970 _transmittedStreams.remove(pInfo->streamID());
1971 }
1972 _currentStreamStopped = false;
1973 _syncStreams();
1974}
1975
1977{
1978 if(hasVideoStream()) {
1979 return _streams.count() > 0;
1980 }
1981 return false;
1982}
1983
1986{
1987 if(_currentStream < _streamLabels.count() && _streamLabels.count()) {
1989 return pStream;
1990 }
1991 return nullptr;
1992}
1993
1996{
1997 //-- For now, it will return the first thermal listed (if any)
1998 for(int i = 0; i < _streams.count(); i++) {
1999 if(_streams[i]) {
2000 QGCVideoStreamInfo* pStream = qobject_cast<QGCVideoStreamInfo*>(_streams[i]);
2001 if(pStream) {
2002 if(pStream->isThermal()) {
2003 return pStream;
2004 }
2005 }
2006 }
2007 }
2008 return nullptr;
2009}
2010
2012{
2013 qCDebug(VehicleCameraControlLog) << "_requestStreamInfo() - stream:" << streamID << "retries:" << _videoStreamInfoRetries;
2014 // By default, try to use new REQUEST_MESSAGE command instead of
2015 // deprecated MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION.
2016 if (_videoStreamInfoRetries % 2 == 0) {
2017 qCDebug(VehicleCameraControlLog) << " Sending REQUEST_MESSAGE:MAVLINK_MSG_ID_VIDEO_STREAM_INFORMATION";
2018 _vehicle->sendMavCommand(
2019 _compID, // target component
2020 MAV_CMD_REQUEST_MESSAGE, // command id
2021 false, // showError
2022 MAVLINK_MSG_ID_VIDEO_STREAM_INFORMATION, // msgid
2023 streamID); // stream ID
2024 } else {
2025 qCDebug(VehicleCameraControlLog) << " Sending MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION (legacy)";
2026 _vehicle->sendMavCommand(
2027 _compID, // Target component
2028 MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION, // Command id
2029 false, // ShowError
2030 streamID); // Stream ID
2031 }
2032 _streamInfoTimer.start(1000); // Wait up to a second for it
2033}
2034
2036{
2037 qCDebug(VehicleCameraControlLog) << "_requestStreamStatus() - stream:" << streamID << "retries:" << _videoStreamStatusRetries;
2038 // By default, try to use new REQUEST_MESSAGE command instead of
2039 // deprecated MAV_CMD_REQUEST_VIDEO_STREAM_STATUS.
2040 if (_videoStreamStatusRetries % 2 == 0) {
2041 qCDebug(VehicleCameraControlLog) << " Sending REQUEST_MESSAGE:MAVLINK_MSG_ID_VIDEO_STREAM_STATUS";
2042 _vehicle->sendMavCommand(
2043 _compID, // target component
2044 MAV_CMD_REQUEST_MESSAGE, // command id
2045 false, // showError
2046 MAVLINK_MSG_ID_VIDEO_STREAM_STATUS, // msgid
2047 streamID); // stream id
2048 } else {
2049 qCDebug(VehicleCameraControlLog) << " Sending MAV_CMD_REQUEST_VIDEO_STREAM_STATUS (legacy)";
2050 _vehicle->sendMavCommand(
2051 _compID, // Target component
2052 MAV_CMD_REQUEST_VIDEO_STREAM_STATUS, // Command id
2053 false, // ShowError
2054 streamID); // Stream ID
2055 }
2056 _streamStatusTimer.start(1000); // Wait up to a second for it
2057}
2058
2061{
2062 for(int i = 0; i < _streams.count(); i++) {
2063 if(_streams[i]) {
2064 QGCVideoStreamInfo* pStream = qobject_cast<QGCVideoStreamInfo*>(_streams[i]);
2065 if(pStream) {
2066 if(pStream->streamID() == id) {
2067 return pStream;
2068 }
2069 } else {
2070 qCritical() << "Null QGCVideoStreamInfo instance";
2071 }
2072 }
2073 }
2074 if(report) {
2075 qWarning() << "Stream id not found:" << id;
2076 }
2077 return nullptr;
2078}
2079
2082{
2083 for(int i = 0; i < _streams.count(); i++) {
2084 if(_streams[i]) {
2085 QGCVideoStreamInfo* pStream = qobject_cast<QGCVideoStreamInfo*>(_streams[i]);
2086 if(pStream) {
2087 if(pStream->name() == name) {
2088 return pStream;
2089 }
2090 }
2091 }
2092 }
2093 return nullptr;
2094}
2095
2097{
2099 int count = _expectedCount * 6;
2100 if(_videoStreamInfoRetries > count) {
2101 qCWarning(VehicleCameraControlLog) << "Giving up requesting video stream info";
2102 _streamInfoTimer.stop();
2103 //-- If we have at least one stream, work with what we have.
2104 if(_streams.count()) {
2105 emit autoStreamChanged();
2106 emit _vehicle->cameraManager()->streamChanged();
2107 }
2108 return;
2109 }
2110 for(uint8_t i = 0; i < _expectedCount; i++) {
2111 //-- Stream ID starts at 1
2112 if(!_findStream(i+1, false)) {
2113 _requestStreamInfo(i+1);
2114 return;
2115 }
2116 }
2117}
2118
2120{
2123 qCWarning(VehicleCameraControlLog) << "Giving up requesting video stream status";
2124 _streamStatusTimer.stop();
2125 return;
2126 }
2128 if(pStream) {
2129 _requestStreamStatus(static_cast<uint8_t>(pStream->streamID()));
2130 }
2131}
2132
2134{
2136 qCDebug(VehicleCameraControlLog) << "_cameraSettingsTimeout() - retries now:" << _cameraSettingsRetries;
2137 if(_cameraSettingsRetries > 5) {
2138 qCWarning(VehicleCameraControlLog) << "Giving up requesting camera settings after" << _cameraSettingsRetries << "retries";
2139 _cameraSettingsTimer.stop();
2140 return;
2141 }
2142 qCDebug(VehicleCameraControlLog) << "_cameraSettingsTimeout() - calling _requestCameraSettings()";
2144}
2145
2147{
2149 qCDebug(VehicleCameraControlLog) << "_storageInfoTimeout() - retries now:" << _storageInfoRetries;
2150 if(_storageInfoRetries > 5) {
2151 qCWarning(VehicleCameraControlLog) << "Giving up requesting storage info after" << _storageInfoRetries << "retries";
2152 _storageInfoTimer.stop();
2153 return;
2154 }
2155 qCDebug(VehicleCameraControlLog) << "_storageInfoTimeout() - calling _requestStorageInfo()";
2157}
2158
2159QStringList
2160VehicleCameraControl::_loadExclusions(QDomNode option)
2161{
2162 QStringList exclusionList;
2163 QDomElement optionElem = option.toElement();
2164 QDomNodeList excRoot = optionElem.elementsByTagName(kExclusions);
2165 if(excRoot.size()) {
2166 //-- Iterate exclusions
2167 QDomNode node = excRoot.item(0);
2168 QDomElement elem = node.toElement();
2169 QDomNodeList exclusions = elem.elementsByTagName(kExclusion);
2170 for(int i = 0; i < exclusions.size(); i++) {
2171 QString exclude = exclusions.item(i).toElement().text();
2172 if(!exclude.isEmpty()) {
2173 exclusionList << exclude;
2174 }
2175 }
2176 }
2177 return exclusionList;
2178}
2179
2180QStringList
2181VehicleCameraControl::_loadUpdates(QDomNode option)
2182{
2183 QStringList updateList;
2184 QDomElement optionElem = option.toElement();
2185 QDomNodeList updateRoot = optionElem.elementsByTagName(kUpdates);
2186 if(updateRoot.size()) {
2187 //-- Iterate updates
2188 QDomNode node = updateRoot.item(0);
2189 QDomElement elem = node.toElement();
2190 QDomNodeList updates = elem.elementsByTagName(kUpdate);
2191 for(int i = 0; i < updates.size(); i++) {
2192 QString update = updates.item(i).toElement().text();
2193 if(!update.isEmpty()) {
2194 updateList << update;
2195 }
2196 }
2197 }
2198 return updateList;
2199}
2200
2201bool VehicleCameraControl::_loadRanges(QDomNode option, const QString factName, QString paramValue)
2202{
2203 QDomElement optionElem = option.toElement();
2204 QDomNodeList rangeRoot = optionElem.elementsByTagName(kParameterranges);
2205 if(rangeRoot.size()) {
2206 QDomNode node = rangeRoot.item(0);
2207 QDomElement elem = node.toElement();
2208 QDomNodeList parameterRanges = elem.elementsByTagName(kParameterrange);
2209 //-- Iterate parameter ranges
2210 for(int i = 0; i < parameterRanges.size(); i++) {
2211 QString param;
2212 QString condition;
2213 QDomNode paramRange = parameterRanges.item(i);
2214 if(!read_attribute(paramRange, kParameter, param)) {
2215 qCritical() << QString("Malformed option range for parameter %1").arg(factName);
2216 return false;
2217 }
2218 read_attribute(paramRange, kCondition, condition);
2219 QDomElement pelem = paramRange.toElement();
2220 QDomNodeList rangeOptions = pelem.elementsByTagName(kRoption);
2221 QStringList optNames;
2222 QStringList optValues;
2223 //-- Iterate options
2224 for(int rangeOptionIndex = 0; rangeOptionIndex < rangeOptions.size(); rangeOptionIndex++) {
2225 QString optName;
2226 QString optValue;
2227 QDomNode roption = rangeOptions.item(rangeOptionIndex);
2228 if(!read_attribute(roption, kName, optName)) {
2229 qCritical() << QString("Malformed roption for parameter %1").arg(factName);
2230 return false;
2231 }
2232 if(!read_attribute(roption, kValue, optValue)) {
2233 qCritical() << QString("Malformed rvalue for parameter %1").arg(factName);
2234 return false;
2235 }
2236 optNames << optName;
2237 optValues << optValue;
2238 }
2239 if(optNames.size()) {
2240 QGCCameraOptionRange* pRange = new QGCCameraOptionRange(this, factName, paramValue, param, condition, optNames, optValues);
2241 _optionRanges.append(pRange);
2242 qCDebug(VehicleCameraControlVerboseLog) << "New range limit:" << factName << paramValue << param << condition << optNames << optValues;
2243 }
2244 }
2245 }
2246 return true;
2247}
2248
2249void VehicleCameraControl::_processRanges()
2250{
2251 //-- After all parameter are loaded, process parameter ranges
2252 for(QGCCameraOptionRange* pRange: _optionRanges) {
2253 Fact* pRFact = getFact(pRange->targetParam);
2254 if(pRFact) {
2255 for(int i = 0; i < pRange->optNames.size(); i++) {
2256 QVariant optVariant;
2257 QString errorString;
2258 if (!pRFact->metaData()->convertAndValidateRaw(pRange->optValues[i], false, optVariant, errorString)) {
2259 qWarning() << "Invalid roption value, name:" << pRange->targetParam
2260 << " type:" << pRFact->metaData()->type()
2261 << " value:" << pRange->optValues[i]
2262 << " error:" << errorString;
2263 } else {
2264 pRange->optVariants << optVariant;
2265 }
2266 }
2267 }
2268 }
2269}
2270
2271bool VehicleCameraControl::_loadNameValue(QDomNode option, const QString factName, FactMetaData* metaData, QString& optName, QString& optValue, QVariant& optVariant)
2272{
2273 if(!read_attribute(option, kName, optName)) {
2274 qCritical() << QString("Malformed option for parameter %1").arg(factName);
2275 return false;
2276 }
2277 if(!read_attribute(option, kValue, optValue)) {
2278 qCritical() << QString("Malformed value for parameter %1").arg(factName);
2279 return false;
2280 }
2281 QString errorString;
2282 if (!metaData->convertAndValidateRaw(optValue, false, optVariant, errorString)) {
2283 qWarning() << "Invalid option value, name:" << factName
2284 << " type:" << metaData->type()
2285 << " value:" << optValue
2286 << " error:" << errorString;
2287 }
2288 return true;
2289}
2290
2291void VehicleCameraControl::_handleDefinitionFile(const QString &url)
2292{
2293 //-- First check and see if we have it cached
2294 QFile xmlFile(_cacheFile);
2295
2296 QString ftpPrefix(QStringLiteral("%1://").arg(FTPManager::mavlinkFTPScheme));
2297 if (!xmlFile.exists() && url.startsWith(ftpPrefix, Qt::CaseInsensitive)) {
2298 qCDebug(VehicleCameraControlLog) << "No camera definition file cached, attempt ftp download";
2299 QString ext = "";
2300 if (url.endsWith(".lzma", Qt::CaseInsensitive)) { ext = ".lzma"; }
2301 if (url.endsWith(".xz", Qt::CaseInsensitive)) { ext = ".xz"; }
2302 // Built from the sanitised token, not from the raw vendor/model strings, so the
2303 // vehicle cannot steer FTPManager's toDir.filePath() join out of the cache folder.
2304 QString fileName = _cacheFileToken + QStringLiteral(".xml") + ext;
2305 connect(_vehicle->ftpManager(), &FTPManager::downloadComplete, this,
2306 &VehicleCameraControl::_ftpDownloadComplete);
2307 if (!_vehicle->ftpManager()->download(
2309 qCWarning(VehicleCameraControlLog) << "Could not start camera definition ftp download:" << url;
2310 disconnect(_vehicle->ftpManager(), &FTPManager::downloadComplete, this,
2311 &VehicleCameraControl::_ftpDownloadComplete);
2312 emit dataReady(QByteArray());
2313 }
2314 return;
2315 }
2316
2317 if (!xmlFile.exists()) {
2318 qCDebug(VehicleCameraControlLog) << "No camera definition file cached, attempt http download";
2319 _httpRequest(url);
2320 return;
2321 }
2322 if (!xmlFile.open(QIODevice::ReadOnly)) {
2323 qWarning() << "Could not read cached camera definition file:" << _cacheFile;
2324 _httpRequest(url);
2325 return;
2326 }
2327 QByteArray bytes = xmlFile.readAll();
2328 QDomDocument doc;
2329 const QDomDocument::ParseResult result = doc.setContent(bytes, QDomDocument::ParseOption::Default);
2330 if (!result) {
2331 qWarning() << "Could not parse cached camera definition file:" << _cacheFile;
2332 _httpRequest(url);
2333 return;
2334 }
2335 //-- We have it
2336 qCDebug(VehicleCameraControlLog) << "Using cached camera definition file:" << _cacheFile;
2337 _cached = true;
2338 emit dataReady(bytes);
2339}
2340
2341void VehicleCameraControl::_httpRequest(const QString &url)
2342{
2343 qCDebug(VehicleCameraControlLog) << "Request camera definition:" << url;
2344 if(!_netManager) {
2345 _netManager = new QNetworkAccessManager(this);
2346 }
2348 QNetworkRequest request(QUrl::fromUserInput(url));
2349 request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true);
2350 QSslConfiguration conf = request.sslConfiguration();
2351 conf.setPeerVerifyMode(QSslSocket::VerifyNone);
2352 request.setSslConfiguration(conf);
2353 QNetworkReply* reply = _netManager->get(request);
2354 connect(reply, &QNetworkReply::finished, this, &VehicleCameraControl::_downloadFinished);
2355}
2356
2358{
2359 QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
2360 if(!reply) {
2361 return;
2362 }
2363 int err = reply->error();
2364 int http_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
2365 QByteArray data = reply->readAll();
2366 if(err == QNetworkReply::NoError && http_code == 200) {
2367 data.append("\n");
2368 } else {
2369 data.clear();
2370 qWarning() << QString("Camera Definition (%1) download error: %2 status: %3").arg(
2371 reply->url().toDisplayString(),
2372 reply->errorString(),
2373 reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
2374 );
2375 }
2376 emit dataReady(data);
2377 //reply->deleteLater();
2378}
2379
2380void VehicleCameraControl::_ftpDownloadComplete(const QString& fileName, const QString& errorMsg)
2381{
2382 qCDebug(VehicleCameraControlLog) << "FTP Download completed: " << fileName << ", " << errorMsg;
2383
2384 disconnect(_vehicle->ftpManager(), &FTPManager::downloadComplete, this, &VehicleCameraControl::_ftpDownloadComplete);
2385
2386 QString outputFileName = QGCCompression::decompressIfNeeded(fileName);
2387 if (outputFileName.isEmpty()) {
2388 qCWarning(VehicleCameraControlLog) << "Inflate of compressed xml failed" << fileName;
2389 }
2390
2391 QFile xmlFile(outputFileName);
2392
2393 if (!xmlFile.exists()) {
2394 qCDebug(VehicleCameraControlLog) << "No camera definition file present after ftp download completed";
2395 return;
2396 }
2397 if (!xmlFile.open(QIODevice::ReadOnly)) {
2398 qWarning() << "Could not read downloaded camera definition file: " << fileName;
2399 return;
2400 }
2401
2402 _cached = true;
2403 QByteArray bytes = xmlFile.readAll();
2404 emit dataReady(bytes);
2405}
2406
2408{
2409 if(data.size()) {
2410 qCDebug(VehicleCameraControlLog) << "Parsing camera definition";
2411 _loadCameraDefinitionFile(data);
2412 } else {
2413 qCDebug(VehicleCameraControlLog) << "No camera definition received, trying to search on our own...";
2414 QFile definitionFile;
2415 if(QGCCorePlugin::instance()->getOfflineCameraDefinitionFile(_modelName, definitionFile)) {
2416 qCDebug(VehicleCameraControlLog) << "Found offline definition file for: " << _modelName << ", loading: " << definitionFile.fileName();
2417 if (definitionFile.open(QIODevice::ReadOnly)) {
2418 QByteArray newData = definitionFile.readAll();
2419 _loadCameraDefinitionFile(newData);
2420 } else {
2421 qCDebug(VehicleCameraControlLog) << "error opening offline definition file for: " << _modelName;
2422 }
2423 } else {
2424 qCDebug(VehicleCameraControlLog) << "No offline camera definition file found";
2425 }
2426 }
2428}
2429
2431{
2432 for(const QString& param: _paramIO.keys()) {
2433 if(!_paramIO[param]->paramDone()) {
2434 return;
2435 }
2436 }
2437 //-- All parameters loaded (or timed out)
2438 _paramComplete = true;
2439 emit parametersReady();
2440}
2441
2443{
2444 if(_mavlinkCameraInfo.flags & CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM) {
2445 connect(&_streamInfoTimer, &QTimer::timeout, this, &VehicleCameraControl::_streamInfoTimeout);
2446 _streamInfoTimer.setSingleShot(false);
2447 connect(&_streamStatusTimer, &QTimer::timeout, this, &VehicleCameraControl::_streamStatusTimeout);
2448 _streamStatusTimer.setSingleShot(true);
2449 //-- Request all streams
2451 _streamInfoTimer.start(2000);
2452 }
2453}
2454
2455bool VehicleCameraControl::incomingParameter(Fact* pFact, QVariant& newValue)
2456{
2457 Q_UNUSED(pFact);
2458 Q_UNUSED(newValue);
2459 return true;
2460}
2461
2462bool VehicleCameraControl::validateParameter(Fact* pFact, QVariant& newValue)
2463{
2464 Q_UNUSED(pFact);
2465 Q_UNUSED(newValue);
2466 return true;
2467}
2468
2469QStringList
2471{
2472 qCDebug(VehicleCameraControlLog) << "Active:" << _activeSettings;
2473 return _activeSettings;
2474}
2475
2476Fact*
2481
2482Fact*
2484{
2485 return (_paramComplete && _activeSettings.contains(kCAM_EV)) ? getFact(kCAM_EV) : nullptr;
2486}
2487
2488Fact*
2490{
2491 return (_paramComplete && _activeSettings.contains(kCAM_ISO)) ? getFact(kCAM_ISO) : nullptr;
2492}
2493
2494Fact*
2499
2500Fact*
2505
2506Fact*
2508{
2509 return (_paramComplete && _activeSettings.contains(kCAM_WBMODE)) ? getFact(kCAM_WBMODE) : nullptr;
2510}
2511
2512Fact*
2517
2519{
2520 if (_trackingEnabled == set) {
2521 return;
2522 }
2523 _trackingEnabled = set;
2524 if (!set) {
2525 stopTracking();
2526 }
2528}
2529
2531{
2533 qCCritical(VehicleCameraControlLog) << "startTrackingRect called but camera does not have rectangle tracking capability";
2534 return;
2535 }
2536
2537 qCDebug(VehicleCameraControlLog) << "Start Tracking (Rectangle: ["
2538 << static_cast<float>(rec.x()) << ", "
2539 << static_cast<float>(rec.y()) << "] - ["
2540 << static_cast<float>(rec.x() + rec.width()) << ", "
2541 << static_cast<float>(rec.y() + rec.height()) << "]";
2542
2543 _vehicle->sendMavCommand(_compID,
2544 MAV_CMD_CAMERA_TRACK_RECTANGLE,
2545 true,
2546 static_cast<float>(rec.x()),
2547 static_cast<float>(rec.y()),
2548 static_cast<float>(rec.x() + rec.width()),
2549 static_cast<float>(rec.y() + rec.height()));
2550
2552}
2553
2554void VehicleCameraControl::startTrackingPoint(QPointF point, double radius)
2555{
2557 qCCritical(VehicleCameraControlLog) << "startTrackingPoint called but camera does not have point tracking capability";
2558 return;
2559 }
2560
2561 qCDebug(VehicleCameraControlLog) << "Start Tracking (Point: ["
2562 << static_cast<float>(point.x()) << ", "
2563 << static_cast<float>(point.y()) << "], Radius: "
2564 << static_cast<float>(radius);
2565
2566 _vehicle->sendMavCommand(_compID,
2567 MAV_CMD_CAMERA_TRACK_POINT,
2568 true,
2569 static_cast<float>(point.x()),
2570 static_cast<float>(point.y()),
2571 static_cast<float>(radius));
2572
2574}
2575
2577{
2578 qCDebug(VehicleCameraControlLog) << "Stop Tracking";
2579
2580 //-- Stop Tracking
2581 _vehicle->sendMavCommand(_compID,
2582 MAV_CMD_CAMERA_STOP_TRACKING,
2583 true);
2584
2585 //-- Stop Sending Tracking Status
2586 _vehicle->sendMavCommand(_compID,
2587 MAV_CMD_SET_MESSAGE_INTERVAL,
2588 true,
2589 MAVLINK_MSG_ID_CAMERA_TRACKING_IMAGE_STATUS,
2590 -1);
2591
2592 // reset tracking state
2593 _trackingImageRect = {};
2597 _trackingImageIsActive = false;
2599 }
2601 _trackingImageIsPoint = false;
2603 }
2604}
2605
2607{
2608 _vehicle->sendMavCommand(_compID,
2609 MAV_CMD_SET_MESSAGE_INTERVAL,
2610 true,
2611 MAVLINK_MSG_ID_CAMERA_TRACKING_IMAGE_STATUS,
2612 500000); // Interval (us)
2613}
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct __mavlink_video_stream_information_t mavlink_video_stream_information_t
struct __mavlink_storage_information_t mavlink_storage_information_t
struct __mavlink_param_ext_value_t mavlink_param_ext_value_t
struct __mavlink_param_ext_ack_t mavlink_param_ext_ack_t
struct __mavlink_camera_information_t mavlink_camera_information_t
struct __mavlink_camera_settings_t mavlink_camera_settings_t
struct __mavlink_video_stream_status_t mavlink_video_stream_status_t
struct __mavlink_camera_tracking_image_status_t mavlink_camera_tracking_image_status_t
struct __mavlink_battery_status_t mavlink_battery_status_t
struct __mavlink_camera_capture_status_t mavlink_camera_capture_status_t
static bool read_value(QDomNode &element, const char *tagName, QString &target)
static bool read_attribute(QDomNode &node, const char *tagName, bool &target)
QString parameterSavePath()
static constexpr const char * mavlinkFTPScheme
Definition FTPManager.h:81
void downloadComplete(const QString &file, const QString &errorMsg)
QMap< QString, FactMetaData * > _nameToFactMetaDataMap
Definition FactGroup.h:71
Q_INVOKABLE Fact * getFact(const QString &name) const
Definition FactGroup.cc:73
void _addFactGroup(FactGroup *factGroup, const QString &name)
Definition FactGroup.cc:139
Q_INVOKABLE bool factExists(const QString &name) const
@ return true: if the fact exists in the group
Definition FactGroup.cc:50
void _addFact(Fact *fact, const QString &name)
Definition FactGroup.cc:122
Holds the meta data associated with a Fact.
void setRawUnits(const QString &rawUnits)
void setDecimalPlaces(int decimalPlaces)
void setHasControl(bool bValue)
void setShortDescription(const QString &shortDescription)
void setLongDescription(const QString &longDescription)
void setRawMin(const QVariant &rawMin)
bool convertAndValidateRaw(const QVariant &rawValue, bool convertOnly, QVariant &typedValue, QString &errorString) const
void setWriteOnly(bool bValue)
void setRawDefaultValue(const QVariant &rawDefaultValue)
void setRawMax(const QVariant &rawMax)
void setRawIncrement(double increment)
void addEnumInfo(const QString &name, const QVariant &value)
Used to add new values to the enum lists after the meta data has been loaded.
QVariant rawDefaultValue() const
ValueType_t type() const
static ValueType_t stringToType(const QString &typeString, bool &unknownType)
void setReadOnly(bool bValue)
A Fact is used to hold a single value within the system.
Definition Fact.h:15
void setMetaData(FactMetaData *metaData, bool setDefaultFromMetaData=false)
Definition Fact.cc:742
void containerSetRawValue(const QVariant &value)
Value coming from Vehicle. This does NOT send a _containerRawValueChanged signal.
Definition Fact.cc:199
FactMetaData * metaData()
Definition Fact.h:172
void setRawValue(const QVariant &value)
Definition Fact.cc:135
QString rawValueString() const
Definition Fact.cc:484
QStringList enumStrings() const
Definition Fact.cc:294
QString name() const
Definition Fact.h:124
static int getComponentId()
static MAVLinkProtocol * instance()
PhotoCaptureStatus _photoCaptureStatus() const
QString captureImageStatusToStr(uint8_t image_status)
VideoCaptureStatus _videoCaptureStatus() const
MavlinkCameraControlInterface(Vehicle *vehicle, QObject *parent=nullptr)
QString captureVideoStatusToStr(uint8_t video_status)
void dataReady(const QByteArray &data)
static MissionCommandTree * instance()
QString rawName(MAV_CMD command) const
Returns the raw name for the specified command.
Camera option exclusions.
QGCCameraOptionExclusion(QObject *parent, QString param_, QString value_, QStringList exclusions_)
QGCCameraOptionRange(QObject *parent, QString param_, QString value_, QString targetParam_, QString condition_, QStringList optNames_, QStringList optValues_)
static QGCCorePlugin * instance()
Encapsulates the contents of a VIDEO_STREAM_INFORMATION message.
quint8 streamID() const
bool update(const mavlink_video_stream_status_t &info)
static SettingsManager * instance()
AppSettings * appSettings() const
virtual void _mavCommandResult(quint32 vehicleId, int component, int command, int result, int failureCode)
void handleParamExtValue(const mavlink_param_ext_value_t &paramExtValue) override
static constexpr const char * kCAM_ISO
void setPhotoLapse(qreal interval) override
static constexpr const char * kRoption
QSize resolution() const override
bool incomingParameter(Fact *pFact, QVariant &newValue) override
Allow controller to modify or invalidate incoming parameter.
QString storageFreeStr() const override
bool capturesPhotos() const override
Q_INVOKABLE void startZoom(int direction) override
bool _currentStreamStopped
Between stopStream() and resumeStream(): the current stream isn't one to transmit.
static constexpr const char * kName
void setTrackingEnabled(bool set) override
QStringList activeSettings() const override
QList< QGCCameraOptionRange * > _optionRanges
static constexpr const char * kType
static constexpr const char * kModel
void setCameraMode(CameraMode cameraMode) override
Q_INVOKABLE void startTrackingRect(QRectF rec) override
Q_INVOKABLE void startTrackingPoint(QPointF point, double radius) override
bool validateParameter(Fact *pFact, QVariant &newValue) override
Allow controller to modify or invalidate parameter change.
mavlink_camera_tracking_image_status_t _trackingImageStatus
QGCVideoStreamInfo * thermalStreamInstance() override
static constexpr const char * kDescription
QString recordTimeStr() const override
Q_INVOKABLE void formatCard(int id=1) override
bool hasVideoStream() const override
virtual void _onVideoManagerRecordingChanged(bool recording)
int compID() const override
static constexpr const char * kUpdate
void setPhotoCaptureMode(PhotoCaptureMode mode) override
QmlObjectListModel _streams
CapturePhotosState capturePhotosState() const override
Q_INVOKABLE void toggleCameraMode() override
void setFocusLevel(qreal level) override
Q_INVOKABLE void stepFocus(int direction) override
Q_INVOKABLE void stepZoom(int direction) override
static constexpr const char * kDecimalPlaces
static constexpr const char * kOptions
bool hasTracking() const override
Q_INVOKABLE bool toggleVideoRecording() override
virtual void _dataReady(QByteArray data)
static QString cacheFileToken(const QString &vendor, const QString &modelName, int definitionVersion)
Q_INVOKABLE bool takePhoto() override
static constexpr const char * kControl
static constexpr const char * kVersion
void setZoomLevel(qreal level) override
void handleVideoStreamInformation(const mavlink_video_stream_information_t &videoStreamInformation) override
QString vendor() const override
bool capturesVideo() const override
static constexpr const char * kWriteOnly
QString batteryRemainingStr() const override
VehicleCameraControl(const mavlink_camera_information_t *info, Vehicle *vehicle, int compID, QObject *parent=nullptr)
static constexpr const char * kCAM_EXPMODE
virtual void _cameraSettingsTimeout()
static constexpr const char * kPhotoLapse
void handleCameraCaptureStatus(const mavlink_camera_capture_status_t &cameraCaptureStatus) override
static constexpr const char * kCAM_APERTURE
static constexpr const char * kTranslated
Q_INVOKABLE void startFocus(int direction) override
bool autoStream() const override
static constexpr const char * kParameterranges
void setThermalOpacity(double val) override
void handleBatteryStatus(const mavlink_battery_status_t &bs) override
static constexpr const char * kUnit
Q_INVOKABLE void stopFocus() override
QSet< quint8 > _transmittedStreams
The streams the camera is taken to transmit: its first one, which it is never asked to start,...
static constexpr const char * kDefnition
static constexpr const char * kVendor
static constexpr const char * kOriginal
void setPhotoLapseCount(int count) override
QList< QGCCameraOptionExclusion * > _valueExclusions
QSizeF sensorSize() const override
Q_INVOKABLE void setCameraModePhoto() override
static constexpr const char * kCAM_SHUTTERSPD
virtual void _requestTrackingStatus()
static constexpr const char * kDefault
static constexpr const char * kMin
qreal focalLength() const override
virtual void _setCameraMode(CameraMode mode)
virtual void _requestStreamInfo(uint8_t streamID)
Q_INVOKABLE bool stopVideoRecording() override
void factChanged(Fact *pFact) override
Notify controller a parameter has changed.
void handleVideoStreamStatus(const mavlink_video_stream_status_t &videoStreamStatus) override
QMap< QString, QGCCameraParamIO * > _paramIO
static constexpr const char * kPhotoLapseCount
static constexpr const char * kExclusions
static constexpr const char * kLocale
int version() const override
static constexpr const char * kCondition
static constexpr const char * kThermalMode
bool hasFocus() const override
Q_INVOKABLE void stopStream() override
static constexpr const char * kMax
QString firmwareVersion() const override
static constexpr const char * kStep
Q_INVOKABLE void resetSettings() override
virtual void _requestStreamStatus(uint8_t streamID)
Q_INVOKABLE bool startVideoRecording() override
Q_INVOKABLE void setCameraModeVideo() override
void handleParamExtAck(const mavlink_param_ext_ack_t &paramExtAck) override
static constexpr const char * kOption
void handleTrackingImageStatus(const mavlink_camera_tracking_image_status_t &trackingImageStatus) override
static QString pathSafeNameToken(const QString &name)
static constexpr const char * kExclusion
void setThermalMode(ThermalViewMode mode) override
static constexpr const char * kStrings
QMap< QString, QVariantList > _originalOptValues
QMap< QString, QStringList > _originalOptNames
static constexpr const char * kPhotoMode
static constexpr const char * kReadOnly
virtual void _requestCaptureStatus()
void handleStorageInformation(const mavlink_storage_information_t &storageInformation) override
bool hasModes() const override
bool trackingEnabled() const override
QString _cacheFileToken
sanitised "<vendor>_<model>_<hash>_<NNN>", no extension
static constexpr const char * kParameter
static constexpr const char * kValue
virtual QGCVideoStreamInfo * _findStream(uint8_t streamID, bool report=true)
CaptureVideoState captureVideoState() const override
static constexpr const char * kUpdates
void handleCameraSettings(const mavlink_camera_settings_t &settings) override
QMap< QString, QStringList > _requestUpdates
Q_INVOKABLE void stopTracking() override
static constexpr const char * kParameterrange
static constexpr const char * kParameters
Q_INVOKABLE void resumeStream() override
bool photosInVideoMode() const override
quint32 recordTime() const override
virtual void _requestCameraSettings()
static constexpr const char * kCAM_EV
bool isBasic() const override
bool hasZoom() const override
Q_INVOKABLE bool stopTakePhoto() override
void setCurrentStream(int stream) override
QNetworkAccessManager * _netManager
bool videoInPhotoMode() const override
Q_INVOKABLE void stopZoom() override
static constexpr const char * kLocalization
static bool pathIsInside(const QString &baseDirPath, const QString &candidateFilePath)
QString modelName() const override
virtual void _setPhotoCaptureStatus(PhotoCaptureStatus captureStatus)
static constexpr const char * kCAM_WBMODE
QGCVideoStreamInfo * currentStreamInstance() override
virtual void _setVideoCaptureStatus(VideoCaptureStatus captureStatus)
void setExtraStreams(const QList< quint8 > &streamIds) override
mavlink_camera_information_t _mavlinkCameraInfo
static constexpr const char * kCAM_MODE
static constexpr const char * kThermalOpacity
FTPManager * ftpManager()
Definition Vehicle.h:603
void mavCommandResult(quint32 vehicleId, int targetComponent, int command, int ackResult, int failureCode)
Q_INVOKABLE void stopRecording()
static VideoManager * instance()
Q_INVOKABLE void startRecording(const QString &baseName=QString())
See VideoRecordingService::startRecording().
void recordingChanged(bool recording)
Q_INVOKABLE void grabImage(const QString &imageFile=QString())
QString decompressIfNeeded(const QString &filePath, const QString &outputPath, bool removeOriginal)
void configureProxy(QNetworkAccessManager *manager)
Set up default proxy configuration on a network manager.
QString numberToString(quint64 number)
Decimal integer (e.g. "1,234,567").
Definition QGCFormat.cc:15
bool runningUnitTests()
QString bigSizeMBToString(quint64 sizeMB)
MB-scaled size, output in MB/GB/TB. Input is in MB.
Definition QGCFormat.cc:38
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9
GPSCommandSequence::Command command(QByteArrayView body, GPSTextMatcher reply, std::chrono::milliseconds timeout)
body labelled by its text, framed as a sentence, and completed by reply within timeout.