远程遥控相关

This commit is contained in:
2026-11-06 08:34:19 +08:00
parent eb8dec2868
commit d882db7995
42 changed files with 5023 additions and 631 deletions

View File

@@ -0,0 +1,199 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/entities/device_control_mode.dart';
import '../../domain/usecases/device_control_mode_usecases.dart';
enum ControlModeEntryPhase { ready, submitting, failed, confirmed }
class ControlModeEntryState {
const ControlModeEntryState({
this.phase = ControlModeEntryPhase.ready,
this.reading,
this.error,
this.errorKey,
});
final ControlModeEntryPhase phase;
final DeviceControlModeReading? reading;
final String? error;
final String? errorKey;
bool get busy => phase == ControlModeEntryPhase.submitting;
bool get canConfirm =>
!busy &&
phase != ControlModeEntryPhase.confirmed &&
errorKey != 'invalid_device';
}
/// 用户确定后下发模式;接口成功即允许进入,不等待设备模式回推。
/// 实时模式只展示设备上报值,不用请求目标覆盖它。
class ControlModeEntryCubit extends Cubit<ControlModeEntryState> {
ControlModeEntryCubit({
required this.deviceId,
required this.target,
required this.watchMode,
required this.changeMode,
this.timeout = const Duration(seconds: 12),
}) : super(const ControlModeEntryState());
final String deviceId;
final ControlModeTarget target;
final WatchDeviceControlModeUseCase watchMode;
final ChangeDeviceControlModeUseCase changeMode;
final Duration timeout;
StreamSubscription<DeviceControlModeReading>? _subscription;
int _generation = 0;
void _trace(String stage, [Map<String, Object?> details = const {}]) {
try {
debugPrint(
'[控制模式切换][$stage] ${jsonEncode({'time': DateTime.now().toIso8601String(), 'deviceId': deviceId, 'currentRawMode': state.reading?.rawMode, 'parsedMode': state.reading?.value, 'targetMode': target.value, 'phase': state.phase.name, 'confirmEnabled': state.canConfirm, ...details})}',
);
} catch (_) {
// 诊断输出不能影响模式下发。
}
}
Future<void> start() async {
++_generation;
final previous = _subscription;
if (previous != null) unawaited(previous.cancel());
if (isClosed) return;
emit(const ControlModeEntryState());
_trace('开始读取实时模式');
if (deviceId.trim().isEmpty) {
_trace('设备编码为空,禁止下发');
emit(
const ControlModeEntryState(
phase: ControlModeEntryPhase.failed,
errorKey: 'invalid_device',
),
);
return;
}
_subscription = watchMode(deviceId).listen(
_onReading,
onError: (Object error) {
if (!isClosed &&
!state.busy &&
state.phase != ControlModeEntryPhase.confirmed) {
emit(
ControlModeEntryState(
phase: ControlModeEntryPhase.failed,
reading: state.reading,
error: '$error',
),
);
}
},
);
}
void _onReading(DeviceControlModeReading reading) {
if (state.reading == null || state.reading?.rawMode != reading.rawMode) {
_trace('实时模式收到', {
'receivedDeviceId': reading.deviceId,
'receivedRawMode': reading.rawMode,
});
}
if (isClosed ||
reading.deviceId != deviceId ||
state.phase == ControlModeEntryPhase.confirmed)
return;
emit(
ControlModeEntryState(
phase: state.phase,
reading: reading,
error: state.error,
errorKey: state.errorKey,
),
);
}
Future<void> confirm() async {
_trace('点击确定');
if (isClosed || !state.canConfirm) {
_trace('点击被忽略', {
'closed': isClosed,
'reason': state.busy ? '请求发送中,防止重复下发' : '设备无效或页面已关闭',
});
return;
}
if (state.reading?.matches(target) == true) {
_trace('模式已符合,跳过接口');
_allowEntry('reported_match');
return;
}
final generation = ++_generation;
emit(
ControlModeEntryState(
phase: ControlModeEntryPhase.submitting,
reading: state.reading,
),
);
_trace('开始下发', {'deviceIdType': deviceId.runtimeType.toString()});
try {
final result = await changeMode(deviceId, target).timeout(timeout);
if (isClosed || generation != _generation) {
_trace('忽略迟到的接口结果', {'closed': isClosed});
return;
}
result.fold((failure) {
_trace('接口失败', {'message': failure.message});
emit(
ControlModeEntryState(
phase: ControlModeEntryPhase.failed,
reading: state.reading,
error: failure.message,
),
);
}, (_) => _allowEntry('http_success'));
} on TimeoutException {
_trace('请求超时', {'timeoutMs': timeout.inMilliseconds});
if (!isClosed && generation == _generation) {
emit(
ControlModeEntryState(
phase: ControlModeEntryPhase.failed,
reading: state.reading,
errorKey: 'request_timeout',
),
);
}
} catch (error) {
_trace('提交异常', {'error': '$error'});
if (!isClosed && generation == _generation) {
emit(
ControlModeEntryState(
phase: ControlModeEntryPhase.failed,
reading: state.reading,
error: '$error',
),
);
}
}
}
void _allowEntry(String source) {
_trace('允许进入', {
'source': source,
'note': source == 'http_success' ? '接口成功,不等待模式回推' : '实时模式已符合',
});
debugPrint(
'[控制模式] 允许进入 deviceId=$deviceId, target=${target.value}, source=$source, reportedMode=${state.reading?.rawMode}',
);
emit(
ControlModeEntryState(
phase: ControlModeEntryPhase.confirmed,
reading: state.reading,
),
);
}
@override
Future<void> close() {
_generation++;
final cancelled = _subscription?.cancel();
final closed = super.close();
if (cancelled == null) return closed;
return Future.wait<void>([cancelled, closed]).then((_) {});
}
}

View File

@@ -0,0 +1,220 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../components/control_mode_text.dart';
import '../../../../core/di/injection.dart';
import '../../../../core/localization/app_localizations.dart';
import '../../domain/entities/device_control_mode.dart';
import '../../domain/usecases/device_control_mode_usecases.dart';
import '../cubit/control_mode_entry_cubit.dart';
Future<bool> showControlModeEntryDialog(
BuildContext context, {
required String deviceId,
required ControlModeTarget target,
String? deviceName,
ControlModeEntryCubit? cubit,
}) async {
final entry =
cubit ??
ControlModeEntryCubit(
deviceId: deviceId,
target: target,
watchMode: sl<WatchDeviceControlModeUseCase>(),
changeMode: sl<ChangeDeviceControlModeUseCase>(),
);
try {
entry.start();
return await showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (_) => BlocProvider.value(
value: entry,
child: _ControlModeEntryDialog(deviceName: deviceName),
),
) ??
false;
} finally {
unawaited(entry.close());
}
}
/// 当前模式已符合或切换接口成功后进入;不改动摇杆归零与停止协议。
class ControlModeEntryGate extends StatefulWidget {
const ControlModeEntryGate({
super.key,
required this.deviceId,
required this.target,
required this.child,
this.deviceName,
this.onReady,
});
final String deviceId;
final String? deviceName;
final ControlModeTarget target;
final Widget child;
final VoidCallback? onReady;
@override
State<ControlModeEntryGate> createState() => _ControlModeEntryGateState();
}
class _ControlModeEntryGateState extends State<ControlModeEntryGate> {
bool _ready = false;
bool _cancelled = false;
bool _entering = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _enter());
}
Future<void> _enter() async {
if (!mounted || _entering || _ready) return;
_entering = true;
setState(() => _cancelled = false);
try {
final accepted = await showControlModeEntryDialog(
context,
deviceId: widget.deviceId,
deviceName: widget.deviceName,
target: widget.target,
);
if (!mounted) return;
if (accepted) {
setState(() => _ready = true);
widget.onReady?.call();
} else {
final popped = await Navigator.of(context).maybePop();
if (!popped && mounted) setState(() => _cancelled = true);
}
} finally {
_entering = false;
}
}
@override
Widget build(BuildContext context) => Stack(
fit: StackFit.expand,
children: [
IgnorePointer(ignoring: !_ready, child: widget.child),
if (_cancelled)
ColoredBox(
color: Colors.black54,
child: Center(
child: FilledButton(
onPressed: _enter,
child: Text(
AppLocalizations.of(
context,
).translate('device_control_mode.retry'),
),
),
),
),
],
);
}
class _ControlModeEntryDialog extends StatelessWidget {
const _ControlModeEntryDialog({this.deviceName});
final String? deviceName;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
String tr(String key) => l10n.translate('device_control_mode.$key');
final cubit = context.read<ControlModeEntryCubit>();
return BlocConsumer<ControlModeEntryCubit, ControlModeEntryState>(
listenWhen: (previous, current) =>
previous.phase != current.phase ||
previous.reading?.rawMode != current.reading?.rawMode ||
previous.canConfirm != current.canConfirm,
listener: (context, state) {
debugPrint(
'[控制模式切换][弹窗状态] deviceId=${cubit.deviceId}, currentRawMode=${state.reading?.rawMode}, targetMode=${cubit.target.value}, phase=${state.phase.name}, confirmEnabled=${state.canConfirm}',
);
if (state.phase == ControlModeEntryPhase.confirmed) {
Navigator.of(context).pop(true);
}
},
builder: (context, state) {
final matches = state.reading?.matches(cubit.target) == true;
final targetText = controlModeDisplayText(
l10n,
'${cubit.target.value}',
);
return PopScope(
canPop: !state.busy,
child: AlertDialog(
title: Text(tr('title')),
content: SizedBox(
width: 380,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
deviceName?.trim().isNotEmpty == true
? '$deviceName · ${cubit.deviceId}'
: cubit.deviceId,
),
const SizedBox(height: 12),
Text(
'${tr('current')}:${controlModeDisplayText(l10n, state.reading?.rawMode)}',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 8),
Text('${tr('target')}:$targetText'),
const SizedBox(height: 12),
Text(
state.busy
? tr('submitting')
: matches
? tr('matched')
: state.reading?.hasReportedMode == true
? tr('mismatch').replaceAll('%s', targetText)
: tr('unknown_mode').replaceAll('%s', targetText),
),
if (state.error != null || state.errorKey != null) ...[
const SizedBox(height: 10),
Text(
state.errorKey != null
? tr(state.errorKey!)
: state.error!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
],
if (state.busy) ...[
const SizedBox(height: 12),
const LinearProgressIndicator(),
],
],
),
),
),
actions: [
TextButton(
onPressed: state.busy
? null
: () => Navigator.of(context).pop(false),
child: Text(l10n.translate('common.back')),
),
if (state.phase == ControlModeEntryPhase.failed &&
state.errorKey != 'invalid_device')
TextButton(onPressed: cubit.start, child: Text(tr('retry'))),
FilledButton(
onPressed: state.canConfirm ? cubit.confirm : null,
child: Text(l10n.translate('common.ok')),
),
],
),
);
},
);
}
}