QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
FailureInjectionComponent.qml
Go to the documentation of this file.
1import QtQuick
2import QtQuick.Controls
3import QtQuick.Layouts
4
5import QGroundControl
6import QGroundControl.Controls
7import QGroundControl.FactControls
8
9import "FailureInjectionInstances.js" as Instances
10
11// Injects failures with MAV_CMD_INJECT_FAILURE; PX4 needs SYS_FAILURE_EN=1 and a reboot first.
12SetupPage {
13 id: failureInjectionPage
14 pageComponent: pageComponent
15
16 // ---- state / model ------------------------------------------------------
17
18 property var _vehicle: controller.vehicle
19 property Fact _sysFailureEn: controller.getParameterFact(-1, "SYS_FAILURE_EN", true /* reportMissing */)
20 property bool _failureInjectionEnabled: _sysFailureEn && _sysFailureEn.value === 1
21
22 // FAILURE_UNIT / FAILURE_TYPE sourced from the MAVLink dialect via the C++ singleton
23 // (enum values + names track common.xml).
24 property var _units: FailureInjection.units // [{ name, unit }]
25 property var _types: FailureInjection.types // [{ name, type }]
26
27 property int _unitIndex: Instances.indexOfUnit(_units, MAVLinkEnums.FAILURE_UNIT_SENSOR_GPS)
28 property int _typeIndex: Instances.indexOfType(_types, MAVLinkEnums.FAILURE_TYPE_OFF)
29 property var _selectedInstances: [1] // 1-based instance numbers
30 readonly property int _instanceCount: 8 // fixed number of selectable instances (not tied to the unit)
31
32 // Detail parameters for the selected unit/type combo (e.g. BATTERY + WRONG -> SYS_FAIL_BAT_LVL).
33 // Re-evaluates when either picker updates _unitIndex/_typeIndex.
34 property var _detailParams: (_unitIndex >= 0 && _unitIndex < _units.length &&
35 _typeIndex >= 0 && _typeIndex < _types.length)
36 ? FailureInjection.detailParams(_units[_unitIndex].unit, _types[_typeIndex].type)
37 : []
38
39 // Activity log column widths — shared by the header and every row so the fields line up.
40 readonly property real _colTimeWidth: ScreenTools.defaultFontPixelWidth * 9
41 readonly property real _colUnitWidth: ScreenTools.defaultFontPixelWidth * 17
42 readonly property real _colTypeWidth: ScreenTools.defaultFontPixelWidth * 15
43
44 FactPanelController { id: controller }
45 QGCPalette { id: qgcPal; colorGroupEnabled: true }
46
47 // Activity log + injected-unit set live in the FailureInjection singleton so they
48 // persist across navigating away from / back to this page (which recreates the QML).
49
50 // Holds MAV_CMD_INJECT_FAILURE sends not yet dispatched. Each entry is sent only once the
51 // previous one's ack has come back through onMavCommandResult/_onAck, so at most one is ever
52 // in flight at a time.
53 property var _sendQueue: [] // outstanding sends: [{ unit, type, param3, param4, logArgs|null }]
54
55 Connections {
56 target: _vehicle
57 function onMavCommandResult(vehicleId, targetComponent, command, ackResult, failureCode) {
58 if (command === MAVLinkEnums.MAV_CMD_INJECT_FAILURE) {
59 _onAck(ackResult, failureCode)
60 }
61 }
62 }
63
64 // ---- behaviour ----------------------------------------------------------
65
66 function _injectOne(unitEnum, typeEnum, param3, param4) {
67 if (!_vehicle) {
68 return
69 }
70 // sendCommand is the QML-callable form of sendMavCommand. Target the component
71 // that owns SYS_FAILURE_EN (the autopilot); fall back to component 1.
72 var compId = _sysFailureEn ? _sysFailureEn.componentId : 1
73 // param3 = instance (0 = all, NaN = use bitmask), param4 = instance bitmask (bit 0 = instance 1).
74 // showError=false: the ack result is surfaced via the mavCommandResult handler (per-row status).
75 _vehicle.sendCommand(compId,
76 MAVLinkEnums.MAV_CMD_INJECT_FAILURE,
77 false, // showError
78 unitEnum, typeEnum, param3, param4, // param1..4
79 0, 0, 0) // param5..7
80 }
81
82 function _instanceSend() {
83 return Instances.instanceSend(_selectedInstances)
84 }
85
86 // Queue one command; kick off sending if the queue was idle.
87 function _enqueueSend(item) {
88 var q = _sendQueue.slice()
89 q.push(item)
90 _sendQueue = q
91 if (q.length === 1) {
92 _sendCurrent()
93 }
94 }
95
96 // Send the head of the queue. Injections and resets both log a row; only injections track the unit.
97 function _sendCurrent() {
98 if (!_failureInjectionEnabled) {
99 // The enable gate closed while sends were queued: drop queued injections, but keep resets so an
100 // injected failure can still be cleared.
101 _sendQueue = _sendQueue.filter(function(item) { return !(item.logArgs && item.logArgs.track) })
102 }
103 if (_sendQueue.length === 0) {
104 return
105 }
106 var s = _sendQueue[0]
107 if (s.logArgs) {
108 var stamp = Qt.formatDateTime(new Date(), "hh:mm:ss")
109 if (s.logArgs.track) {
110 // injection: log the row and remember the unit for Reset
111 FailureInjection.logInjection(s.logArgs.unitName, s.logArgs.typeName, s.unit,
112 s.logArgs.instanceLabel, stamp)
113 } else {
114 // reset OK: log the row but don't re-track the unit
115 FailureInjection.logRow(s.logArgs.unitName, s.logArgs.typeName, s.logArgs.instanceLabel, stamp)
116 }
117 }
118 _injectOne(s.unit, s.type, s.param3, s.param4)
119 }
120
121 // One ack arrived: resolve the matching log row (only one is pending at a time), then send the next.
122 function _onAck(ackResult, failureCode) {
123 var acked = _sendQueue.length > 0 ? _sendQueue[0] : null // head is the send being acked
124 // resolves the oldest pending row; failureCode separates "rejected" from "never answered"
125 FailureInjection.resolveResult(ackResult, failureCode)
126 // An accepted reset (track:false) untracks its unit — on ack, not up front, so an interrupted
127 // Reset all keeps the rest retryable.
128 if (acked && acked.logArgs && !acked.logArgs.track && ackResult === MAVLinkEnums.MAV_RESULT_ACCEPTED) {
129 FailureInjection.markUnitReset(acked.unit)
130 }
131 if (_sendQueue.length > 0) {
132 var q = _sendQueue.slice()
133 q.shift()
134 _sendQueue = q
135 }
136 _sendCurrent()
137 }
138
139 function _apply() {
140 if (!_failureInjectionEnabled || _selectedInstances.length === 0) {
141 return
142 }
143 var u = _units[_unitIndex]
144 var t = _types[_typeIndex]
145 var send = _instanceSend() // one command covers all selected instances (bitmask when >1)
146 _enqueueSend({ unit: u.unit, type: t.type, param3: send.param3, param4: send.param4,
147 logArgs: { unitName: u.name, typeName: t.name, instanceLabel: send.label, track: true } })
148 }
149
150 function _toggleInstance(n) {
151 _selectedInstances = Instances.toggleInstance(_selectedInstances, n)
152 }
153
154 function _unitName(unitEnum) {
155 return Instances.unitName(_units, unitEnum)
156 }
157
158 function _typeName(typeEnum) {
159 return Instances.typeName(_types, typeEnum)
160 }
161
162 // Send FAILURE_TYPE_OK (all instances) to every injected unit, including injections still queued (a unit is
163 // only tracked once sent); each is untracked on its accepted ack (see _onAck), so an interrupted Reset all
164 // leaves the rest retryable. Activity list is kept.
165 function _resetAll() {
166 var injected = FailureInjection.injectedUnits() // Q_INVOKABLE method — needs the call parentheses
167 for (var q = 0; q < _sendQueue.length; ++q) {
168 var queued = _sendQueue[q]
169 if (queued.logArgs && queued.logArgs.track && injected.indexOf(queued.unit) < 0) {
170 injected.push(queued.unit)
171 }
172 }
173 for (var i = 0; i < injected.length; ++i) {
174 _enqueueSend({ unit: injected[i], type: MAVLinkEnums.FAILURE_TYPE_OK, param3: 0 /* all instances */,
175 param4: 0,
176 logArgs: { unitName: _unitName(injected[i]),
177 typeName: _typeName(MAVLinkEnums.FAILURE_TYPE_OK),
178 instanceLabel: "all", track: false } })
179 }
180 }
181
182 // ---- page ---------------------------------------------------------------
183
184 Component {
185 id: pageComponent
186
187 ColumnLayout {
188 width: availableWidth
189 spacing: ScreenTools.defaultFontPixelHeight
190
191 // On (re)load: clear the session if the vehicle changed while the page was unloaded, then
192 // resolve any row left "pending" when a prior page instance was destroyed mid-send.
193 Component.onCompleted: {
194 FailureInjection.notifyActiveVehicle(_vehicle ? _vehicle.id : 0)
195 FailureInjection.resolvePendingInterrupted()
196 }
197
198 QGCLabel {
199 Layout.fillWidth: true
200 wrapMode: Text.WordWrap
201 text: qsTr("Injects simulated failures into flight components (sensors, GPS, motors, " +
202 "and more) to test failsafe behavior. " +
203 "Use with care — an injected failure affects the vehicle immediately.")
204 }
205
206 // ---- SYS_FAILURE_EN gate + reboot ----------------------------------
207 QGCGroupBox {
208 heading: qsTr("Failure Injection")
209 showDividers: false
210
211 RowLayout {
212 Layout.fillWidth: true
213 spacing: ScreenTools.defaultFontPixelWidth * 2
214
215 QGCCheckBox {
216 objectName: "failureInjection_enableCheckbox"
217 text: qsTr("SYS_FAILURE_EN")
218 enabled: _sysFailureEn !== null
219 checked: _failureInjectionEnabled
220 onClicked: _sysFailureEn.value = checked ? 1 : 0
221 }
222 QGCLabel {
223 objectName: "failureInjection_enabledLabel"
224 Layout.fillWidth: true
225 color: qgcPal.colorGreen
226 visible: _failureInjectionEnabled
227 text: qsTr("Failure injection enabled.")
228 }
229 }
230 }
231
232 // ---- builder -------------------------------------------------------
233 QGCGroupBox {
234 heading: qsTr("Inject Failure")
235 showDividers: false
236 enabled: _failureInjectionEnabled
237
238 RowLayout {
239 Layout.fillWidth: true
240 spacing: ScreenTools.defaultFontPixelWidth * 2
241
242 ColumnLayout {
243 QGCLabel { text: qsTr("Component") }
244 QGCComboBox {
245 id: unitCombo
246 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 24
247 model: _units.map(function(u){ return u.name })
248 currentIndex: _unitIndex
249 onActivated: function(index) {
250 _unitIndex = index
251 _selectedInstances = [1] // reset selection on unit change
252 }
253 }
254 }
255 ColumnLayout {
256 QGCLabel { text: qsTr("Failure type") }
257 QGCComboBox {
258 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 18
259 model: _types.map(function(t){ return t.name })
260 currentIndex: _typeIndex
261 onActivated: function(index) { _typeIndex = index }
262 }
263 }
264 // Detail parameters for the selected combo, styled like the pickers to their
265 // left. Each editor appears only when the vehicle exposes the parameter:
266 // enum metadata -> dropdown, otherwise numeric field.
267 Repeater {
268 model: _detailParams
269 ColumnLayout {
270 id: detailCol
271 property Fact _detailFact: controller.parameterExists(-1, modelData.param)
272 ? controller.getParameterFact(-1, modelData.param,
273 false /* reportMissing */)
274 : null
275 visible: detailCol._detailFact !== null
276
277 QGCLabel { text: modelData.label }
278 FactComboBox {
279 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 18
280 fact: detailCol._detailFact
281 indexModel: false
282 visible: detailCol._detailFact !== null &&
283 detailCol._detailFact.enumStrings.length > 0
284 }
285 FactTextField {
286 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 18
287 fact: detailCol._detailFact
288 visible: detailCol._detailFact !== null &&
289 detailCol._detailFact.enumStrings.length === 0
290 }
291 }
292 }
293 Item { Layout.fillWidth: true }
294 QGCButton {
295 objectName: "failureInjection_injectButton"
296 text: qsTr("Inject failure")
297 primary: true
298 enabled: _failureInjectionEnabled && _selectedInstances.length > 0
299 onClicked: _apply()
300 }
301 }
302
303 // multi-select instances ("All" = instance 0 = every instance of the unit)
304 QGCLabel { text: qsTr("Instances — select one or more, or All") }
305 Flow {
306 Layout.fillWidth: true
307 spacing: ScreenTools.defaultFontPixelWidth * 2
308 Repeater {
309 model: _instanceCount
310 QGCCheckBox {
311 text: qsTr("i = %1").arg(index + 1)
312 checked: _selectedInstances.indexOf(index + 1) >= 0
313 onClicked: _toggleInstance(index + 1)
314 }
315 }
316 // vertical divider, then the "All" toggle, left-aligned right after the instances
317 Rectangle {
318 width: 1
319 height: ScreenTools.defaultFontPixelHeight * 1.5
320 color: qgcPal.textPrimary
321 opacity: 0.3
322 }
323 QGCCheckBox {
324 text: qsTr("All (i = 0)")
325 checked: _selectedInstances.indexOf(0) >= 0
326 // "All" is exclusive: selecting it clears specific instances, and vice versa
327 onClicked: _selectedInstances = checked ? [0] : []
328 }
329 }
330
331 // live command preview
332 QGCLabel {
333 Layout.fillWidth: true
334 font.family: ScreenTools.fixedFontFamily
335 color: qgcPal.colorGreen
336 wrapMode: Text.WordWrap
337 text: {
338 if (_selectedInstances.length === 0) {
339 return qsTr("MAV_CMD_INJECT_FAILURE param1=%1 param2=%2 (no instance selected)")
340 .arg(_units[_unitIndex].unit).arg(_types[_typeIndex].type)
341 }
342 var u = _units[_unitIndex]
343 var t = _types[_typeIndex]
344 var s = _instanceSend()
345 var p3 = isNaN(s.param3) ? "NaN" : s.param3
346 return qsTr("MAV_CMD_INJECT_FAILURE param1=%1 param2=%2 param3=%3 param4=%4 (i=%5)")
347 .arg(u.unit).arg(t.type).arg(p3).arg(s.param4).arg(s.label)
348 }
349 }
350 }
351
352 // ---- activity log ---------------------------------------------------
353 QGCGroupBox {
354 heading: qsTr("Activity")
355 showDividers: false
356
357 RowLayout {
358 Layout.fillWidth: true
359 QGCLabel { Layout.fillWidth: true; text: qsTr("Newest first") }
360 QGCButton {
361 objectName: "failureInjection_resetAllButton"
362 text: qsTr("Reset all")
363 onClicked: _resetAll()
364 }
365 }
366 // Column header, aligned with the rows below.
367 RowLayout {
368 Layout.fillWidth: true
369 Layout.leftMargin: ScreenTools.defaultFontPixelWidth
370 Layout.rightMargin: ScreenTools.defaultFontPixelWidth
371 spacing: ScreenTools.defaultFontPixelWidth * 2
372 QGCLabel {
373 Layout.preferredWidth: _colTimeWidth
374 font.family: ScreenTools.fixedFontFamily
375 color: qgcPal.textPrimary
376 text: qsTr("Time")
377 }
378 QGCLabel {
379 Layout.preferredWidth: _colUnitWidth
380 font.family: ScreenTools.fixedFontFamily
381 color: qgcPal.textPrimary
382 text: qsTr("Component")
383 }
384 QGCLabel {
385 Layout.preferredWidth: _colTypeWidth
386 font.family: ScreenTools.fixedFontFamily
387 color: qgcPal.textPrimary
388 text: qsTr("Failure")
389 }
390 QGCLabel {
391 Layout.fillWidth: true
392 font.family: ScreenTools.fixedFontFamily
393 color: qgcPal.textPrimary
394 text: qsTr("Instances")
395 }
396 QGCLabel {
397 font.family: ScreenTools.fixedFontFamily
398 color: qgcPal.textPrimary
399 text: qsTr("Result")
400 }
401 }
402 Rectangle {
403 Layout.fillWidth: true
404 Layout.preferredHeight: ScreenTools.defaultFontPixelHeight * 12
405 color: qgcPal.windowCard
406 border.color: qgcPal.borderSubtle
407 radius: ScreenTools.defaultBorderRadius
408
409 QGCListView {
410 objectName: "failureInjection_activityList"
411 anchors.fill: parent
412 anchors.margins: ScreenTools.defaultFontPixelWidth
413 clip: true
414 model: FailureInjection.activity
415 delegate: RowLayout {
416 required property var modelData
417 required property int index
418 readonly property bool _pending: modelData.result === "pending"
419 readonly property bool _accepted: modelData.result === "accepted"
420 objectName: "failureInjection_activityRow_" + index
421 width: ListView.view.width
422 spacing: ScreenTools.defaultFontPixelWidth * 2
423 QGCLabel {
424 Layout.preferredWidth: _colTimeWidth
425 font.family: ScreenTools.fixedFontFamily
426 color: qgcPal.colorOrange
427 text: modelData.time
428 }
429 QGCLabel {
430 objectName: "failureInjection_unitName_" + index
431 Layout.preferredWidth: _colUnitWidth
432 font.family: ScreenTools.fixedFontFamily
433 text: modelData.unitName
434 }
435 QGCLabel {
436 objectName: "failureInjection_typeName_" + index
437 Layout.preferredWidth: _colTypeWidth
438 font.family: ScreenTools.fixedFontFamily
439 text: modelData.typeName
440 }
441 QGCLabel {
442 objectName: "failureInjection_instance_" + index
443 Layout.fillWidth: true
444 font.family: ScreenTools.fixedFontFamily
445 elide: Text.ElideRight
446 text: modelData.instance
447 }
448 QGCLabel {
449 objectName: "failureInjection_result_" + index
450 font.family: ScreenTools.fixedFontFamily
451 color: _pending ? qgcPal.colorOrange
452 : (_accepted ? qgcPal.colorGreen : qgcPal.colorRed)
453 text: _pending ? qsTr("…")
454 : (_accepted ? qsTr("✓ Accepted") : ("× " + modelData.result))
455 }
456 }
457 }
458 }
459 }
460 }
461 }
462}