完善遥控权限、控制发送和急停反馈

This commit is contained in:
2026-11-21 14:37:46 +08:00
parent c284aefc7d
commit 9a8a42a0a1
55 changed files with 5009 additions and 1308 deletions

View File

@@ -0,0 +1,47 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'remote_control_diagnostics.dart';
/// Passive tracing only. Identifiers stay local and never enter HTTP/TCP data.
class ControlPermissionDiagnostics {
static final Object _scopeKey = Object();
static Map<String, Object?>? get context =>
Zone.current[_scopeKey] as Map<String, Object?>?;
static T scope<T>(Map<String, Object?> fields, T Function() action) =>
runZoned(
action,
zoneValues: {_scopeKey: Map<String, Object?>.of(fields)},
);
static Object? scalar(Object? value) =>
value == null || value is String || value is num || value is bool
? value
: '<${value.runtimeType}>';
/// Callers supply whitelisted fields, never tokens, headers, or raw packets.
static void event(String step, [Map<String, Object?> fields = const {}]) {
try {
final trace = RemoteControlDiagnostics.instance;
final record = <String, Object?>{
'time': DateTime.now().toIso8601String(),
...?context,
...fields,
'traceVersion': 1,
'permissionStep': step,
};
final startedUs = record['startedUs'];
if (startedUs is int) {
record['elapsedMs'] = (trace.elapsedUs - startedUs) ~/ 1000;
}
trace.event('permission_trace', record);
debugPrint('[权限链][$step] ${jsonEncode(record)}');
} catch (_) {
// Logging cannot interrupt permission, motion, or safety handling.
}
}
}

View File

@@ -0,0 +1,121 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
/// Passive motion tracing. This class never sends commands or awaits a network
/// operation. File writes are buffered and serialized separately from control.
class RemoteControlDiagnostics {
RemoteControlDiagnostics({Future<void> Function(String)? append})
: _appendOverride = append;
static RemoteControlDiagnostics instance = RemoteControlDiagnostics();
static final Object _frameKey = Object();
final Future<void> Function(String)? _appendOverride;
final Stopwatch _clock = Stopwatch()..start();
final String _run = DateTime.now().microsecondsSinceEpoch.toString();
final List<String> _pending = [];
Future<Directory>? _directory;
Future<void>? _inFlight;
Timer? _flushTimer;
int _sequence = 0;
int _frameSequence = 0;
int _sessionSequence = 0;
int _dropped = 0;
String? activeDevice;
int get elapsedUs => _clock.elapsedMicroseconds;
void begin(String? device, Map<String, Object?> configuration) {
activeDevice = device;
_sessionSequence++;
event('session_start', configuration);
}
void end(String reason) {
event('session_end', {'reason': reason});
activeDevice = null;
unawaited(flush());
}
/// Local correlation only; no identifiers are added to the wire protocol.
T frame<T>(String source, Map<String, Object?> fields, T Function() send) {
final context = <String, Object?>{
'session': _sessionSequence,
'device': activeDevice,
'frame': ++_frameSequence,
'source': source,
...fields,
};
return runZoned(send, zoneValues: {_frameKey: context});
}
void event(String stage, Map<String, Object?> fields) {
try {
final frame = Zone.current[_frameKey] as Map<String, Object?>?;
final record = <String, Object?>{
'time': DateTime.now().toIso8601String(),
'us': elapsedUs,
'run': _run,
'session': _sessionSequence,
'seq': ++_sequence,
'device': activeDevice,
if (frame != null) ...frame,
'stage': stage,
...fields,
};
for (final key in record.keys.toList()) {
final value = record[key];
if (value is double && !value.isFinite) record[key] = value.toString();
}
// A stalled filesystem cannot grow memory without bounds or block control.
if (_pending.length >= 2000) {
_pending.removeAt(0);
_dropped++;
}
_pending.add('${jsonEncode(record)}\n');
_flushTimer ??= Timer(const Duration(milliseconds: 500), () {
_flushTimer = null;
unawaited(flush());
});
} catch (_) {
// Diagnostics must never interrupt an input, control or safety callback.
}
}
Future<void> _append(String content) async {
final override = _appendOverride;
if (override != null) return override(content);
final directory = await (_directory ??= getApplicationDocumentsDirectory());
final day = DateTime.now().toIso8601String().substring(0, 10);
await File(
'${directory.path}/remote_control_$day.jsonl',
).writeAsString(content, mode: FileMode.append);
}
Future<void> flush() {
_flushTimer?.cancel();
_flushTimer = null;
return _inFlight ??= _drain().whenComplete(() => _inFlight = null);
}
Future<void> _drain() async {
while (_pending.isNotEmpty) {
final dropped = _dropped;
_dropped = 0;
final batch = _pending.join();
_pending.clear();
try {
await _append(
'${dropped == 0 ? '' : '${jsonEncode({'stage': 'diagnostic_overflow', 'dropped': dropped})}\n'}$batch',
);
} catch (_) {
// Mark missing records in the next successful write instead of silently
// making a logging failure look like a gap in TCP transmission.
_dropped += dropped + '\n'.allMatches(batch).length;
return;
}
}
}
}