远程遥控相关

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((_) {});
}
}