6import QGroundControl.Controls
7import QGroundControl.FactControls
9import "FailureInjectionInstances.js" as Instances
11// Injects failures with MAV_CMD_INJECT_FAILURE; PX4 needs SYS_FAILURE_EN=1 and a reboot first.
13 id: failureInjectionPage
14 pageComponent: pageComponent
16 // ---- state / model ------------------------------------------------------
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
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 }]
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)
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)
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
44 FactPanelController { id: controller }
45 QGCPalette { id: qgcPal; colorGroupEnabled: true }
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).
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 }]
57 function onMavCommandResult(vehicleId, targetComponent, command, ackResult, failureCode) {
58 if (command === MAVLinkEnums.MAV_CMD_INJECT_FAILURE) {
59 _onAck(ackResult, failureCode)
64 // ---- behaviour ----------------------------------------------------------
66 function _injectOne(unitEnum, typeEnum, param3, param4) {
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,
78 unitEnum, typeEnum, param3, param4, // param1..4
82 function _instanceSend() {
83 return Instances.instanceSend(_selectedInstances)
86 // Queue one command; kick off sending if the queue was idle.
87 function _enqueueSend(item) {
88 var q = _sendQueue.slice()
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) })
103 if (_sendQueue.length === 0) {
106 var s = _sendQueue[0]
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)
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)
118 _injectOne(s.unit, s.type, s.param3, s.param4)
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)
131 if (_sendQueue.length > 0) {
132 var q = _sendQueue.slice()
140 if (!_failureInjectionEnabled || _selectedInstances.length === 0) {
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 } })
150 function _toggleInstance(n) {
151 _selectedInstances = Instances.toggleInstance(_selectedInstances, n)
154 function _unitName(unitEnum) {
155 return Instances.unitName(_units, unitEnum)
158 function _typeName(typeEnum) {
159 return Instances.typeName(_types, typeEnum)
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)
173 for (var i = 0; i < injected.length; ++i) {
174 _enqueueSend({ unit: injected[i], type: MAVLinkEnums.FAILURE_TYPE_OK, param3: 0 /* all instances */,
176 logArgs: { unitName: _unitName(injected[i]),
177 typeName: _typeName(MAVLinkEnums.FAILURE_TYPE_OK),
178 instanceLabel: "all", track: false } })
182 // ---- page ---------------------------------------------------------------
188 width: availableWidth
189 spacing: ScreenTools.defaultFontPixelHeight
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()
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.")
206 // ---- SYS_FAILURE_EN gate + reboot ----------------------------------
208 heading: qsTr("Failure Injection")
212 Layout.fillWidth: true
213 spacing: ScreenTools.defaultFontPixelWidth * 2
216 objectName: "failureInjection_enableCheckbox"
217 text: qsTr("SYS_FAILURE_EN")
218 enabled: _sysFailureEn !== null
219 checked: _failureInjectionEnabled
220 onClicked: _sysFailureEn.value = checked ? 1 : 0
223 objectName: "failureInjection_enabledLabel"
224 Layout.fillWidth: true
225 color: qgcPal.colorGreen
226 visible: _failureInjectionEnabled
227 text: qsTr("Failure injection enabled.")
232 // ---- builder -------------------------------------------------------
234 heading: qsTr("Inject Failure")
236 enabled: _failureInjectionEnabled
239 Layout.fillWidth: true
240 spacing: ScreenTools.defaultFontPixelWidth * 2
243 QGCLabel { text: qsTr("Component") }
246 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 24
247 model: _units.map(function(u){ return u.name })
248 currentIndex: _unitIndex
249 onActivated: function(index) {
251 _selectedInstances = [1] // reset selection on unit change
256 QGCLabel { text: qsTr("Failure type") }
258 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 18
259 model: _types.map(function(t){ return t.name })
260 currentIndex: _typeIndex
261 onActivated: function(index) { _typeIndex = index }
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.
271 property Fact _detailFact: controller.parameterExists(-1, modelData.param)
272 ? controller.getParameterFact(-1, modelData.param,
273 false /* reportMissing */)
275 visible: detailCol._detailFact !== null
277 QGCLabel { text: modelData.label }
279 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 18
280 fact: detailCol._detailFact
282 visible: detailCol._detailFact !== null &&
283 detailCol._detailFact.enumStrings.length > 0
286 Layout.preferredWidth: ScreenTools.defaultFontPixelWidth * 18
287 fact: detailCol._detailFact
288 visible: detailCol._detailFact !== null &&
289 detailCol._detailFact.enumStrings.length === 0
293 Item { Layout.fillWidth: true }
295 objectName: "failureInjection_injectButton"
296 text: qsTr("Inject failure")
298 enabled: _failureInjectionEnabled && _selectedInstances.length > 0
303 // multi-select instances ("All" = instance 0 = every instance of the unit)
304 QGCLabel { text: qsTr("Instances — select one or more, or All") }
306 Layout.fillWidth: true
307 spacing: ScreenTools.defaultFontPixelWidth * 2
309 model: _instanceCount
311 text: qsTr("i = %1").arg(index + 1)
312 checked: _selectedInstances.indexOf(index + 1) >= 0
313 onClicked: _toggleInstance(index + 1)
316 // vertical divider, then the "All" toggle, left-aligned right after the instances
319 height: ScreenTools.defaultFontPixelHeight * 1.5
320 color: qgcPal.textPrimary
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] : []
331 // live command preview
333 Layout.fillWidth: true
334 font.family: ScreenTools.fixedFontFamily
335 color: qgcPal.colorGreen
336 wrapMode: Text.WordWrap
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)
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)
352 // ---- activity log ---------------------------------------------------
354 heading: qsTr("Activity")
358 Layout.fillWidth: true
359 QGCLabel { Layout.fillWidth: true; text: qsTr("Newest first") }
361 objectName: "failureInjection_resetAllButton"
362 text: qsTr("Reset all")
363 onClicked: _resetAll()
366 // Column header, aligned with the rows below.
368 Layout.fillWidth: true
369 Layout.leftMargin: ScreenTools.defaultFontPixelWidth
370 Layout.rightMargin: ScreenTools.defaultFontPixelWidth
371 spacing: ScreenTools.defaultFontPixelWidth * 2
373 Layout.preferredWidth: _colTimeWidth
374 font.family: ScreenTools.fixedFontFamily
375 color: qgcPal.textPrimary
379 Layout.preferredWidth: _colUnitWidth
380 font.family: ScreenTools.fixedFontFamily
381 color: qgcPal.textPrimary
382 text: qsTr("Component")
385 Layout.preferredWidth: _colTypeWidth
386 font.family: ScreenTools.fixedFontFamily
387 color: qgcPal.textPrimary
388 text: qsTr("Failure")
391 Layout.fillWidth: true
392 font.family: ScreenTools.fixedFontFamily
393 color: qgcPal.textPrimary
394 text: qsTr("Instances")
397 font.family: ScreenTools.fixedFontFamily
398 color: qgcPal.textPrimary
403 Layout.fillWidth: true
404 Layout.preferredHeight: ScreenTools.defaultFontPixelHeight * 12
405 color: qgcPal.windowCard
406 border.color: qgcPal.borderSubtle
407 radius: ScreenTools.defaultBorderRadius
410 objectName: "failureInjection_activityList"
412 anchors.margins: ScreenTools.defaultFontPixelWidth
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
424 Layout.preferredWidth: _colTimeWidth
425 font.family: ScreenTools.fixedFontFamily
426 color: qgcPal.colorOrange
430 objectName: "failureInjection_unitName_" + index
431 Layout.preferredWidth: _colUnitWidth
432 font.family: ScreenTools.fixedFontFamily
433 text: modelData.unitName
436 objectName: "failureInjection_typeName_" + index
437 Layout.preferredWidth: _colTypeWidth
438 font.family: ScreenTools.fixedFontFamily
439 text: modelData.typeName
442 objectName: "failureInjection_instance_" + index
443 Layout.fillWidth: true
444 font.family: ScreenTools.fixedFontFamily
445 elide: Text.ElideRight
446 text: modelData.instance
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))