Batch the Fly App's telemetry and split it per subsystem

The GO 4-style HUD needs far more live data than the bridge sent, and
pushing every SDK callback straight to Dart would rebuild the screen
dozens of times a second. This is the telemetry foundation (plan P1).

On the Kotlin side, every source now writes into a TelemetryHub that
emits one telemetry event per tick: flight-controller state, gimbal and
vision at up to 10 Hz, battery, links, RC, storage and camera settings
folded in at up to 2 Hz. Each event carries the full latest snapshot, so
a consumer that drops packets never loses a slow group. New bridges
cover batteries (every pack, cell voltages, warning thresholds), link
quality and RC battery, diagnostics, and obstacle sensing per sensor.
KeyBridge adds generic getKey/setKey/listenKey over KeyManager for the
settings rows to come. The flight controller also gains smart-RTH
confirmation and simulator start/stop.

On the Dart side, FlightModel now owns one ChangeNotifier per subsystem
(aircraft, battery, links, camera, gimbal, vision, alerts, mission), so
a HUD widget can listen to just the one it draws. TelemetryReducer
routes events into them, only notifies groups that changed, and gives
FlightModel one notification per tick. Flat getters keep the existing
screens working. Diagnostics become graded, de-duplicated alerts.
Settings > About > Telemetry inspector shows every field live and can
start the simulator.

Battery no longer arrives as its own event, so the API Server reads the
percentage from the telemetry snapshot (the old event is still accepted).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-19 18:34:56 +02:00
1 parent a8483ecf45
commit f6bbb1cfee
28 files changed
+2716 -187

No files matched your search

+165
View File
@@ -0,0 +1,165 @@
/// Synthetic bridge events in the shape `TelemetryHub.kt` and the sub-bridges
/// emit, standing in for a simulator recording until one is captured (plan §4).
library;
/// A Phantom 4-like aircraft hovering at 32 m, all groups reported.
Map<String, dynamic> telemetryTick({
int battery = 64,
double altitude = 32.4,
double gimbalPitch = -30,
int uplink = 88,
double noseDistance = 6.5,
String? smartRTHState = 'IDLE',
}) =>
<String, dynamic>{
'type': 'telemetry',
'satelliteCount': 17,
'gpsSignalLevel': 5,
'isFlying': true,
'areMotorsOn': true,
'flightMode': 'P-GPS',
'flightModeEnum': 'GPS_ATTI',
'altitude': altitude,
'latitude': 55.6761,
'longitude': 12.5683,
'homeLatitude': 55.6760,
'homeLongitude': 12.5680,
'isHomeLocationSet': true,
'homeDistance': 21.3,
'horizontalSpeed': 0.2,
'verticalSpeed': -0.1,
'heading': 87.5,
'pitch': -1.2,
'roll': 0.4,
'yaw': 87.5,
'goHomeHeight': 60,
'velocityX': 0.1,
'velocityY': 0.15,
'velocityZ': 0.1,
'flightTimeSeconds': 245,
'ultrasonicHeight': double.nan,
'isUltrasonicBeingUsed': false,
'ultrasonicError': false,
'isVisionPositioningBeingUsed': false,
'isLandingConfirmationNeeded': false,
'isGoingHome': false,
'goHomeExecutionState': 'NOT_EXECUTING',
'isLowBattery': false,
'isSeriousLowBattery': false,
'batteryThresholdBehavior': 'FLY_NORMALLY',
'windWarning': 'LEVEL_0',
'reachedMaxHeight': false,
'reachedMaxRadius': false,
'isIMUPreheating': false,
'isFailsafe': false,
'orientationMode': 'AIRCRAFT_HEADING',
'goHome': <Object?, Object?>{
'remainingFlightTime': 780,
'timeNeededToGoHome': 40,
'timeNeededToLand': 22,
'batteryNeededToGoHome': 12,
'batteryNeededToLand': 6,
'maxRadiusCanFlyAndGoHome': 2400.0,
'smartRTHState': smartRTHState,
'smartRTHCountdown': 0,
},
'gimbal': <Object?, Object?>{'pitch': gimbalPitch, 'roll': 0.0, 'yaw': 87.0},
'vision': <Object?, Object?>{
'NOSE': <Object?, Object?>{
'isSensorBeingUsed': true,
'isDisabled': false,
'systemWarning': 'SAFE',
'distance': noseDistance,
'avoidAlertLevel': 0,
'sectors': <Object?>[
<Object?, Object?>{'distance': 9.0, 'warningLevel': 'LEVEL_1'},
<Object?, Object?>{'distance': noseDistance, 'warningLevel': 'LEVEL_2'},
<Object?, Object?>{'distance': 12.0, 'warningLevel': 'LEVEL_1'},
<Object?, Object?>{'distance': 15.0, 'warningLevel': 'INVALID'},
],
},
},
'battery': <Object?, Object?>{
'percent': battery,
'voltage': 15.6,
'temperature': 38.5,
'lowWarningThreshold': 30,
'seriousLowWarningThreshold': 15,
'packs': <Object?>[
<Object?, Object?>{
'index': 0,
'percent': battery,
'voltage': 15.6,
'current': -9.8,
'temperature': 38.5,
'chargeRemainingMah': 3500,
'fullChargeCapacityMah': 5350,
'designCapacityMah': 5870,
'discharges': 42,
'lifetimePercent': 91,
'isCharging': false,
'cellVoltages': <Object?>[3.91, 3.90, 3.92, 3.88],
'cellVoltageLevel': 'LEVEL_0',
'connectionState': 'NORMAL',
},
],
},
'links': <Object?, Object?>{'kind': 'lightbridge', 'uplinkQuality': uplink, 'downlinkQuality': 74},
'rc': <Object?, Object?>{'batteryPercent': 81, 'batteryMah': 4200, 'isCharging': false},
'storage': <Object?, Object?>{
'location': 'SDCARD',
'inserted': true,
'initializing': false,
'formatting': false,
'formatted': true,
'full': false,
'error': false,
'readOnly': false,
'invalidFormat': false,
'verified': true,
'totalMB': 61000,
'remainingMB': 48211,
'availableCaptureCount': 5400,
'availableRecordingSeconds': 7260,
},
'cameraSettings': <Object?, Object?>{
'aeLock': false,
'focusMode': 'AFC',
'photoAspectRatio': 'RATIO_3_2',
'photoFileFormat': 'RAW_AND_JPEG',
'videoResolution': 'RESOLUTION_3840x2160',
'videoFrameRate': 'FRAME_RATE_29_DOT_970_FPS',
'videoFileFormat': 'MOV',
'colorProfile': 'NONE',
},
};
Map<String, dynamic> diagnostics(List<Map<String, Object?>> items) => <String, dynamic>{
'type': 'diagnostics',
'items': items,
};
const Map<String, Object?> compassInterference = <String, Object?>{
'component': 'FLIGHT_CONTROLLER',
'code': 1004,
'subCode': 0,
'componentIndex': 0,
'reason': 'Compass interference.',
'solution': 'Move away from metal objects.',
};
const Map<String, Object?> motorBlocked = <String, Object?>{
'component': 'FLIGHT_CONTROLLER',
'code': 1301,
'componentIndex': 0,
'reason': 'Motor blocked.',
'solution': 'Land and check the propellers.',
};
const Map<String, Object?> sdSlow = <String, Object?>{
'component': 'CAMERA',
'code': 2010,
'componentIndex': 0,
'reason': 'SD card write speed slow.',
'solution': null,
};
+183
View File
@@ -0,0 +1,183 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pilotvault_fly/flight_model.dart';
import 'package:pilotvault_fly/fly/state/alert_state.dart';
import 'package:pilotvault_fly/fly/state/link_state.dart';
import 'package:pilotvault_fly/fly/telemetry_reducer.dart';
import 'package:pilotvault_fly/ui/fly/debug/telemetry_inspector_page.dart';
import 'telemetry_fixtures.dart';
/// Counts notifications from [l].
int Function() counter(Listenable l) {
int n = 0;
l.addListener(() => n++);
return () => n;
}
void main() {
late FlightModel m;
late TelemetryReducer r;
setUp(() {
m = FlightModel()..connected = true;
r = TelemetryReducer(m);
});
group('TelemetryReducer', () {
test('a tick fills every sub-model', () {
expect(r.apply(telemetryTick()), isTrue);
expect(m.aircraft.flightMode, 'P-GPS');
expect(m.aircraft.flightModeEnum, 'GPS_ATTI');
expect(m.aircraft.pitch, -1.2);
expect(m.aircraft.flightTimeSeconds, 245);
expect(m.aircraft.ultrasonicHeight, isNull, reason: 'NaN reads as unreported');
expect(m.aircraft.vpsHeight, isNull);
expect(m.aircraft.goHome!.batteryNeededToGoHome, 12);
expect(m.aircraft.goHome!.remainingFlightTime, 780);
expect(m.battery.percent, 64);
expect(m.battery.lowWarningThreshold, 30);
expect(m.battery.packs.single.cellVoltages, <double>[3.91, 3.90, 3.92, 3.88]);
expect(m.battery.packs.single.cellDeviation, closeTo(0.04, 1e-9));
expect(m.links.uplinkQuality, 88);
expect(m.links.downlinkQuality, 74);
expect(m.links.rcBatteryPercent, 81);
expect(m.camera.storage!.status, 'OK');
expect(m.camera.storage!.availableRecordingSeconds, 7260);
expect(m.camera.focusMode, 'AFC');
expect(m.gimbal.pitch, -30);
expect(m.vision.nose!.sectors, hasLength(4));
expect(m.vision.nose!.sectors[1].level, 2);
expect(m.vision.nose!.sectors[3].level, 0);
expect(m.vision.closest, 6.5);
// Pre-P2 screens read the same values through the flat getters.
expect(m.batteryPercent, 64);
expect(m.altitude, 32.4);
expect(m.gimbalPitch, -30);
expect(m.sdRemainingMB, 48211);
});
test('FlightModel notifies once per tick, not once per sub-model', () {
final int Function() n = counter(m);
r.apply(telemetryTick());
expect(n(), 1);
});
test('an unchanged slow group does not re-notify its sub-model', () {
r.apply(telemetryTick());
final int Function() battery = counter(m.battery);
final int Function() links = counter(m.links);
final int Function() aircraft = counter(m.aircraft);
r.apply(telemetryTick(altitude: 33)); // only flight state moved
expect(aircraft(), 1);
expect(battery(), 0);
expect(links(), 0);
r.apply(telemetryTick(altitude: 33, battery: 63, uplink: 60));
expect(battery(), 1);
expect(links(), 1);
expect(m.battery.percent, 63);
expect(LinkState.bars(m.links.uplinkQuality), 3);
});
test('a group missing from the snapshot leaves its sub-model empty', () {
r.apply(telemetryTick());
final Map<String, dynamic> noVision = telemetryTick()..remove('vision');
r.apply(noVision);
expect(m.vision.sensors, isEmpty);
});
test('telemetry after a disconnect is ignored', () {
m.connected = false;
r.apply(telemetryTick());
expect(m.aircraft.flightMode, isNull);
expect(m.battery.percent, isNull);
});
test('clearTelemetry + reset start the next aircraft from scratch', () {
r.apply(telemetryTick());
m.clearTelemetry();
r.reset();
expect(m.battery.percent, isNull);
expect(m.camera.storage, isNull);
r.apply(telemetryTick());
expect(m.battery.percent, 64, reason: 'same groups as before must re-apply after a reset');
});
test('smart-RTH countdown is visible', () {
r.apply(telemetryTick(smartRTHState: 'COUNTING_DOWN'));
expect(m.aircraft.goHome!.smartRTHCountingDown, isTrue);
});
test('non-telemetry events pass through', () {
expect(r.apply(<String, dynamic>{'type': 'connection', 'connected': true}), isFalse);
expect(r.apply(<String, dynamic>{'type': 'mission', 'state': 'tracking'}), isTrue);
expect(m.tracking, isTrue);
});
});
group('AlertState', () {
test('diagnostics are graded, ordered and de-duplicated', () {
r.apply(diagnostics(<Map<String, Object?>>[compassInterference, sdSlow, motorBlocked, compassInterference]));
final List<DiagnosticAlert> a = m.alerts.all;
expect(a, hasLength(3));
expect(a.first.reason, 'Motor blocked.');
expect(a.first.severity, AlertSeverity.critical);
expect(m.alerts.top!.code, 1301);
expect(a.map((DiagnosticAlert d) => d.severity).skip(1), everyElement(AlertSeverity.warning));
expect(m.alerts.lastAdded, hasLength(3));
});
test('a listed alert keeps its first-seen time; cleared ones drop out', () {
final AlertState s = AlertState();
final DateTime t0 = DateTime(2026, 10, 19, 12);
s.apply(<Map<String, dynamic>>[compassInterference], now: t0);
s.apply(<Map<String, dynamic>>[compassInterference, sdSlow], now: t0.add(const Duration(seconds: 5)));
expect(s.all.firstWhere((DiagnosticAlert d) => d.code == 1004).firstSeen, t0);
expect(s.lastAdded, <String>{'CAMERA/2010/0'});
s.apply(<Map<String, dynamic>>[sdSlow]);
expect(s.all.single.code, 2010);
});
test('a dismissed alert stays hidden until it clears and returns', () {
final AlertState s = AlertState();
s.apply(<Map<String, dynamic>>[sdSlow]);
s.dismiss('CAMERA/2010/0');
expect(s.active, isEmpty);
expect(s.top, isNotNull, reason: 'the marquee still shows it');
s.apply(<Map<String, dynamic>>[sdSlow]);
expect(s.active, isEmpty);
s.apply(const <Map<String, dynamic>>[]);
s.apply(<Map<String, dynamic>>[sdSlow]);
expect(s.active, hasLength(1));
});
test('grading heuristic', () {
expect(AlertState.grade('BATTERY', 'Critically low battery.', null), AlertSeverity.critical);
expect(AlertState.grade('FLIGHT_CONTROLLER', 'IMU preheating.', null), AlertSeverity.info);
expect(AlertState.grade('GIMBAL', 'Gimbal motor overloaded.', null), AlertSeverity.critical);
expect(AlertState.grade('CAMERA', 'SD card write speed slow.', null), AlertSeverity.warning);
});
});
testWidgets('telemetry inspector renders every section from a tick', (WidgetTester tester) async {
r.apply(telemetryTick());
r.apply(diagnostics(<Map<String, Object?>>[motorBlocked]));
await tester.pumpWidget(MaterialApp(home: Scaffold(body: TelemetryInspector(model: m))));
expect(find.text('P-GPS (GPS_ATTI)'), findsOneWidget);
await tester.scrollUntilVisible(find.text('88 / 100'), 300);
expect(find.text('88 / 100'), findsOneWidget);
await tester.scrollUntilVisible(find.text('critical · FLIGHT_CONTROLLER 1301'), 300);
expect(find.text('critical · FLIGHT_CONTROLLER 1301'), findsOneWidget);
await tester.pumpWidget(const SizedBox()); // dispose the timer
});
}