import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/entities/machine_control_status_entity.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/emergency_stop_button.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/emergency_overlay.dart'; import 'package:get_it/get_it.dart'; import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart'; import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart'; import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart'; import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart'; import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart'; import 'package:fpdart/fpdart.dart'; import 'package:maibu_satabot_v2/core/error/failure.dart'; import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_target.dart'; import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_failure.dart'; import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart'; import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart'; import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/entities/control_permission_failure.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart'; import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_control_permission_usecase.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart'; class _Logger implements ILoggerService { @override dynamic noSuchMethod(Invocation invocation) => null; } class _LoadedLocalizations extends LocalizationsDelegate { const _LoadedLocalizations(this.value); final AppLocalizations value; @override bool isSupported(Locale locale) => true; @override Future load(Locale locale) => SynchronousFuture(value); @override bool shouldReload(_LoadedLocalizations old) => false; } class _Devices implements DeviceRepository { @override dynamic noSuchMethod(Invocation invocation) => null; } class _Status implements DeviceStatusBloc { static ({String sn, bool? active, DateTime receivedAt})? reading; @override ({String sn, bool? active, DateTime receivedAt})? get emergencyStopReading => reading; @override dynamic noSuchMethod(Invocation invocation) => null; } class _Tcp implements TcpClient { final packets = StreamController.broadcast(sync: true); bool connected = true; @override bool get isConnected => connected; @override Stream get packetStream => packets.stream; @override dynamic noSuchMethod(Invocation invocation) => null; } class _Dispatcher implements NetMessageDispatcher { _Dispatcher(this.tcp); final _Tcp tcp; @override Stream onCommand(int command) => tcp.packetStream.where((p) => p.command == command); @override dynamic noSuchMethod(Invocation invocation) => null; } class _Repository implements RemoteControlRepository { int motionSends = 0; final sentFrames = []; @override Future sendControlMachineCmd( MachineControlStatusEntity status, { bool priority = false, bool Function()? isCurrent, }) async { if (isCurrent != null && !isCurrent()) return false; motionSends++; sentFrames.add(status); return true; } int queries = 0; int sends = 0; Map info = {'hasPermission': false, 'owner': 'web'}; Completer>? query; Completer? write; ControlPermissionFailure? queryError; ControlPermissionFailure? sendError; @override Future> requestControlPermission( String deviceName, String deviceId, ) async { queries++; if (queryError != null) throw queryError!; return query?.future ?? info; } @override Future sendTcpPermissionRequest( String deviceName, { bool Function()? isCurrent, }) async { if (isCurrent != null && !isCurrent()) return; sends++; if (sendError != null) throw sendError!; await write?.future; } @override dynamic noSuchMethod(Invocation invocation) => null; } class _Cubit extends RemoteControlCubit { _Cubit(_Repository repo, _Tcp tcp, _Emergency emergency) : super( repo, RequestControlPermissionUseCase(repo), _Devices(), tcp, _Dispatcher(tcp), _Status(), requestEmergencyStop: RequestDeviceEmergencyStopUseCase(emergency), emergencyNow: () => TestWidgetsFlutterBinding.instance.clock.now(), ); int stops = 0; @override Future stopAllMovement({String reason = 'unspecified'}) async { stops++; } } class _Emergency implements DeviceEmergencyStopRepository { bool autoReport = true; void Function()? onReport; final calls = <(String, EmergencyStopTarget)>[]; Either result = const Right(unit); Completer>? pending; @override Future> request( String deviceId, EmergencyStopTarget target, ) async { calls.add((deviceId, target)); final response = await (pending?.future ?? Future.value(result)); if (autoReport && response.isRight()) { _Status.reading = ( sn: deviceId, active: target == EmergencyStopTarget.engage, receivedAt: TestWidgetsFlutterBinding.instance.clock.now(), ); onReport?.call(); } return response; } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); late _Emergency emergency; void scenario( String name, Future Function(WidgetTester, _Cubit, _Repository, _Tcp) body, ) { testWidgets(name, (tester) async { GetIt.I.registerSingleton(_Logger()); RemoteControlDiagnostics.instance = RemoteControlDiagnostics( append: (_) async {}, ); final repo = _Repository(); final tcp = _Tcp(); emergency = _Emergency(); _Status.reading = ( sn: 'SN-1', active: false, receivedAt: tester.binding.clock.now(), ); final cubit = _Cubit(repo, tcp, emergency); emergency.onReport = cubit.refreshEmergencyStatus; cubit.emit( cubit.state.copyWith( targetDevice: DeviceEntity( deviceName: 'SN-1', productId: 1, productName: '', tenantId: 1, tenantName: '', ), ), ); try { cubit.refreshEmergencyStatus(); await body(tester, cubit, repo, tcp); } finally { await cubit.close(); await RemoteControlDiagnostics.instance.flush(); await tcp.packets.close(); await tester.pump(const Duration(seconds: 20)); await tester.pumpWidget(const SizedBox.shrink()); await GetIt.I.reset(); } }); } Future request(_Cubit c) => c.requestControlPermissionS('SN-1', 'app', grabControl: true); void respond( _Tcp tcp, dynamic result, { String device = 'SN-1', String? reason, bool crc = true, }) { tcp.packets.add( RawPacket( command: 0x12, payload: Uint8List.fromList([ ...utf8.encode( jsonEncode({ 'respond': { 'deviceId': device, 'switchResult': result, 'holder': 'you', if (reason != null) 'reason': reason, }, }), ), if (crc) ...[0, 0], ]), ), ); } scenario('entry only queries and never sends', (t, c, r, tcp) async { await c.requestControlPermissionS('SN-1', 'app'); expect(r.queries, 1); expect(r.sends, 0); expect(emergency.calls, isEmpty); expect(c.state.permissionRequestPhase, PermissionRequestPhase.idle); }); scenario('manual request sends once and blocks repeat taps', ( t, c, r, tcp, ) async { await request(c); await request(c); expect(r.queries, 1); expect(r.sends, 1); expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting); expect(c.state.permissionFeedbackKey, 'permission_sent'); expect(c.state.hasPermission, isFalse); }); scenario('send notice waits for actual write completion', ( t, c, r, tcp, ) async { r.write = Completer(); final pending = request(c); await t.pump(); expect(c.state.permissionRequestPhase, PermissionRequestPhase.sending); expect(c.state.permissionFeedbackKey, isNot('permission_sent')); r.write!.complete(); await pending; expect(c.state.permissionFeedbackKey, 'permission_sent'); }); scenario( 'manual request with HTTP permission and no owner still sends once', (t, c, r, tcp) async { r.info = {'hasPermission': true, 'owner': null}; await request(c); expect(r.sends, 1); expect(c.state.hasPermission, isFalse); expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting); respond(tcp, true); expect(c.state.hasPermission, isTrue); }, ); scenario('query errors preserve their classification and never send', ( t, c, r, tcp, ) async { r.queryError = ControlPermissionFailure('permission_query_invalid'); await request(c); expect(r.sends, 0); expect(c.state.permissionFeedbackKey, 'permission_query_invalid'); expect(c.state.isPermissionRequestBusy, isFalse); }); scenario('disconnected socket reports not sent', (t, c, r, tcp) async { tcp.connected = false; await request(c); expect(r.sends, 0); expect(c.state.permissionFeedbackKey, 'permission_tcp_disconnected'); }); scenario('write failure reaches the UI', (t, c, r, tcp) async { r.sendError = ControlPermissionFailure('permission_send_uncertain'); await request(c); expect(c.state.permissionFeedbackKey, 'permission_send_uncertain'); expect(c.state.isPermissionRequestBusy, isFalse); }); scenario('matching success updates control and cancels timeout', ( t, c, r, tcp, ) async { await request(c); respond(tcp, true); await t.pump(); expect(c.state.hasPermission, isTrue); expect(c.state.permissionFeedbackKey, 'permission_granted'); await t.pump(const Duration(seconds: 11)); expect(c.state.permissionFeedbackKey, 'permission_granted'); }); scenario('fast response cannot be overwritten by a late write completion', ( t, c, r, tcp, ) async { r.write = Completer(); final pending = request(c); await t.pump(); respond(tcp, true); r.write!.complete(); await pending; expect(c.state.hasPermission, isTrue); expect(c.state.permissionFeedbackKey, 'permission_granted'); expect(c.state.permissionRequestPhase, PermissionRequestPhase.granted); }); scenario('wrong-device and invalid results cannot grant control', ( t, c, r, tcp, ) async { await request(c); respond(tcp, true, device: 'SN-2'); respond(tcp, null); await t.pump(); expect(c.state.hasPermission, isFalse); expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting); }); scenario('explicit denial differs from a generic unsuccessful result', ( t, c, r, tcp, ) async { await request(c); respond(tcp, false); await t.pump(); expect(c.state.permissionFeedbackKey, 'permission_not_granted'); expect(c.stops, 1); await request(c); respond(tcp, false, reason: 'holder_denied'); await t.pump(); expect(c.state.permissionFeedbackKey, 'permission_denied'); }); scenario('result without CRC is accepted', (t, c, r, tcp) async { await request(c); respond(tcp, true, crc: false); await t.pump(); expect(c.state.hasPermission, isTrue); }); scenario('no response times out and permits retry', (t, c, r, tcp) async { await request(c); await t.pump(const Duration(seconds: 11)); expect(c.state.permissionFeedbackKey, 'permission_result_timeout'); expect(c.state.hasPermission, isFalse); expect(c.state.isPermissionRequestBusy, isFalse); await request(c); expect(r.sends, 2); }); scenario('disconnect while waiting is reported as unconfirmed', ( t, c, r, tcp, ) async { await request(c); tcp.connected = false; await t.pump(const Duration(milliseconds: 250)); expect(c.state.permissionFeedbackKey, 'permission_connection_lost'); }); scenario('exit invalidates an outstanding query and late TCP result', ( t, c, r, tcp, ) async { r.query = Completer>(); final pending = request(c); await t.pump(); c.resetPermissionState(); r.query!.complete({'hasPermission': true, 'owner': 'app'}); await pending; respond(tcp, true); await t.pump(); expect(c.state.hasPermission, isFalse); expect(c.state.permissionRequestPhase, PermissionRequestPhase.idle); expect(r.sends, 0); }); scenario('query timeout cannot send a late request', (t, c, r, tcp) async { r.query = Completer>(); final pending = request(c); await t.pump(const Duration(seconds: 11)); await pending; expect(c.state.permissionFeedbackKey, 'permission_query_timeout'); r.query!.complete({'hasPermission': false, 'owner': 'web'}); await t.pump(); expect(r.sends, 0); }); scenario('e-stop uses current SN without TCP or control permission', ( t, c, r, tcp, ) async { tcp.connected = false; c.updateFunction(mower: 1, lift: 1); expect(await c.updateEmergency(true), isTrue); expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]); expect(r.motionSends, 0); expect(c.state.isEmergency, isTrue); expect(c.state.isLocked, isTrue); expect(c.state.controlEntity.isEmergency, isFalse); expect(c.state.controlEntity.mowerSpeed, 0); expect(c.state.controlEntity.chassisLift, 0); expect(c.state.emergencyFeedbackKey, 'emergency_request_sent'); }); scenario('release sends zero and clears local state only after API success', ( t, c, r, tcp, ) async { await c.updateEmergency(true); emergency.pending = Completer>(); final release = c.updateEmergency(false); expect(c.state.isEmergency, isTrue); expect(c.state.isLocked, isTrue); expect(c.state.isEmergencyRequestPending, isTrue); // A late joystick callback must not revive old movement after release. c.updateFunction(mower: 0); emergency.pending!.complete(const Right(unit)); expect(await release, isTrue); expect(emergency.calls.last, ('SN-1', EmergencyStopTarget.release)); expect(c.state.isEmergency, isFalse); expect(c.state.isLocked, isFalse); expect(c.state.controlEntity.originX, 0); expect(c.state.controlEntity.originY, 0); expect(c.state.emergencyFeedbackKey, 'emergency_release_sent'); expect(r.motionSends, 0); }); scenario('repeat taps and release while sending cannot duplicate requests', ( t, c, r, tcp, ) async { emergency.pending = Completer>(); final first = c.updateEmergency(true); expect(await c.updateEmergency(true), isFalse); expect(await c.updateEmergency(false), isFalse); expect(emergency.calls, hasLength(1)); emergency.pending!.complete(const Right(unit)); await first; }); scenario('failed stop keeps local inhibit and permits retry', ( t, c, r, tcp, ) async { emergency.result = Left(NetworkFailure('timeout')); expect(await c.updateEmergency(true), isFalse); expect(c.state.isEmergency, isFalse); expect(c.state.isLocked, isTrue); expect(c.state.emergencyRequestFailed, isTrue); emergency.result = const Right(unit); expect(await c.updateEmergency(true), isTrue); expect(emergency.calls, hasLength(2)); }); scenario('business failure during stop keeps normal UI and permits retry', ( t, c, r, tcp, ) async { c.emit(c.state.copyWith(hasPermission: true)); c.startControlLoop(); emergency.pending = Completer>(); final sending = c.updateEmergency(true); expect(c.state.isEmergencyRequestPending, isTrue); expect(c.state.isEmergency, isFalse); c.toggleLock(); await t.pump(const Duration(milliseconds: 200)); expect(r.motionSends, 0); emergency.pending!.complete(Left(EmergencyStopRejectedFailure('设备模式切换失败'))); expect(await sending, isFalse); expect(c.state.isEmergency, isFalse); expect(c.state.isLocked, isFalse); expect(c.state.isEmergencyRequestPending, isFalse); expect(c.state.emergencyFeedbackKey, 'emergency_request_rejected'); emergency.pending = null; expect(await c.updateEmergency(true), isTrue); expect(c.state.isEmergency, isTrue); }); scenario('business failure during release keeps previous e-stop state', ( t, c, r, tcp, ) async { await c.updateEmergency(true); emergency.result = Left(EmergencyStopRejectedFailure('设备模式切换失败')); expect(await c.updateEmergency(false), isFalse); expect(c.state.isEmergency, isTrue); expect(c.state.isLocked, isTrue); expect(c.state.isEmergencyRequestPending, isFalse); expect(c.state.emergencyRequestFailed, isTrue); }); scenario('missing SN does not send an e-stop request', (t, c, r, tcp) async { c.clearTargetDevice(); expect(await c.updateEmergency(true), isFalse); expect(emergency.calls, isEmpty); expect(c.state.emergencyFeedbackKey, 'emergency_missing_sn'); }); scenario('exiting session does not request release or clear local e-stop', ( t, c, r, tcp, ) async { await c.updateEmergency(true); c.resetPermissionState(); expect(emergency.calls, hasLength(1)); expect(c.state.isEmergency, isTrue); expect(c.state.isLocked, isTrue); }); scenario('late e-stop reply cannot apply after target was cleared', ( t, c, r, tcp, ) async { emergency.pending = Completer>(); final pending = c.updateEmergency(true); c.clearTargetDevice(); emergency.pending!.complete(const Right(unit)); expect(await pending, isFalse); expect(c.state.targetDevice, isNull); expect(c.state.isEmergency, isFalse); expect(c.state.isEmergencyRequestPending, isFalse); }); scenario('motion loop waits 250ms and sends the latest input', ( t, c, r, tcp, ) async { c.emit(c.state.copyWith(hasPermission: true)); c.startControlLoop(); c.updateOriginY(25); await t.pump(const Duration(milliseconds: 200)); expect(r.sentFrames, isEmpty); c.updateOriginY(75); await t.pump(const Duration(milliseconds: 49)); expect(r.sentFrames, isEmpty); await t.pump(const Duration(milliseconds: 1)); expect(r.sentFrames.map((frame) => frame.originY), [75]); c.updateOriginY(50); await t.pump(const Duration(milliseconds: 250)); expect(r.sentFrames.map((frame) => frame.originY), [75, 50]); }); scenario('mower hold repeats every 250ms and release keeps last operation', ( t, c, r, tcp, ) async { expect(c.state.controlEntity.mowerSpeed, 2); c.emit(c.state.copyWith(hasPermission: true)); c.startControlLoop(); c.sendMowerSliderCommand(1); await t.pump(const Duration(milliseconds: 750)); expect(r.sentFrames.map((frame) => frame.mowerSpeed), [1, 1, 1]); expect(c.state.lastMowerOperation, MowerLastOperation.turnOn); c.sendMowerSliderCommand(0); await t.pump(const Duration(milliseconds: 250)); expect(r.sentFrames.last.mowerSpeed, 2); expect(c.state.lastMowerOperation, MowerLastOperation.turnOn); c.sendMowerSliderCommand(2); await t.pump(const Duration(milliseconds: 250)); expect(r.sentFrames.last.mowerSpeed, 0); expect(c.state.lastMowerOperation, MowerLastOperation.turnOff); c.sendMowerSliderCommand(0); await t.pump(const Duration(milliseconds: 250)); expect(r.sentFrames.last.mowerSpeed, 2); expect(c.state.lastMowerOperation, MowerLastOperation.turnOff); expect(c.state.controlEntity.chassisLift, 0); expect(c.state.controlEntity.ignitionStatus, 0); }); scenario('mower session reset clears last operation and pending command', ( t, c, r, tcp, ) async { c.sendMowerSliderCommand(1); c.resetPermissionState(); expect(c.state.lastMowerOperation, MowerLastOperation.none); expect(c.state.controlEntity.mowerSpeed, 2); c.sendMowerSliderCommand(2); c.resetMowerControl(); expect(c.state.lastMowerOperation, MowerLastOperation.none); expect(c.state.controlEntity.mowerSpeed, 2); c.sendMowerSliderCommand(1); c.clearTargetDevice(); expect(c.state.targetDevice, isNull); expect(c.state.lastMowerOperation, MowerLastOperation.none); expect(c.state.controlEntity.mowerSpeed, 2); }); scenario('telemetry controls UI and API success cannot change it', ( t, c, r, tcp, ) async { emergency.autoReport = false; expect(c.state.hasEmergencyStatus, isTrue); expect(c.state.isEmergency, isFalse); expect(await c.updateEmergency(true), isTrue); expect(c.state.isEmergency, isFalse); _Status.reading = ( sn: 'SN-1', active: true, receivedAt: t.binding.clock.now(), ); c.refreshEmergencyStatus(); expect(c.state.isEmergency, isTrue); expect(await c.updateEmergency(true), isFalse); expect(emergency.calls, hasLength(1)); expect(await c.updateEmergency(false), isTrue); expect(c.state.isEmergency, isTrue); _Status.reading = ( sn: 'SN-1', active: false, receivedAt: t.binding.clock.now(), ); c.refreshEmergencyStatus(); expect(c.state.isEmergency, isFalse); }); scenario('telemetry missing stale or from another SN blocks commands', ( t, c, r, tcp, ) async { for (final reading in <({String sn, bool? active, DateTime receivedAt})?>[ null, (sn: 'SN-1', active: null, receivedAt: t.binding.clock.now()), (sn: 'SN-2', active: false, receivedAt: t.binding.clock.now()), ( sn: 'SN-1', active: false, receivedAt: t.binding.clock.now().subtract(const Duration(seconds: 11)), ), ]) { _Status.reading = reading; c.refreshEmergencyStatus(); expect(c.state.hasEmergencyStatus, isFalse); expect(await c.updateEmergency(true), isFalse); expect(await c.updateEmergency(false), isFalse); } expect(emergency.calls, isEmpty); }); Future mountButton(WidgetTester t, _Cubit c) async { final translations = AppLocalizations(AppLocalizations.english); await t.runAsync(translations.load); await t.pumpWidget( MaterialApp( localizationsDelegates: [_LoadedLocalizations(translations)], supportedLocales: AppLocalizations.supportedLocales, locale: AppLocalizations.english, home: BlocProvider.value( value: c, child: Scaffold( body: BlocBuilder( builder: (context, state) => Stack( children: [ if (state.isEmergency) const Positioned.fill(child: EmergencyOverlay()), const Center(child: EmergencyStopButton(width: 180)), ], ), ), ), ), ), ); await t.pumpAndSettle(); } Future confirmDialog(WidgetTester t) async { await t.pump(const Duration(milliseconds: 400)); await t.tap(find.byKey(const ValueKey('emergency-confirm'))); await t.pump(); await t.pump(const Duration(milliseconds: 400)); } scenario('button confirmation sends stop and release and removes breathing', ( t, c, r, tcp, ) async { await mountButton(t, c); await t.tap(find.byType(EmergencyStopButton)); await t.pump(); expect(emergency.calls, isEmpty); expect(find.byType(AlertDialog), findsOneWidget); await confirmDialog(t); await t.pump(); expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]); expect(find.byType(EmergencyOverlay), findsOneWidget); await t.tap(find.byType(EmergencyStopButton)); await t.pump(); expect(emergency.calls, hasLength(1)); expect(find.byType(AlertDialog), findsOneWidget); await confirmDialog(t); expect(emergency.calls.last, ('SN-1', EmergencyStopTarget.release)); expect(emergency.calls, hasLength(2)); expect(find.byType(EmergencyOverlay), findsNothing); expect(r.motionSends, 0); }); scenario( 'cancel stop confirmation sends nothing and does not start breathing', (t, c, r, tcp) async { await mountButton(t, c); await t.tap(find.byType(EmergencyStopButton)); await t.pump(const Duration(milliseconds: 400)); expect(emergency.calls, isEmpty); await t.tap(find.byKey(const ValueKey('emergency-cancel'))); await t.pump(const Duration(milliseconds: 400)); expect(emergency.calls, isEmpty); expect(c.state.isEmergency, isFalse); expect(find.byType(EmergencyOverlay), findsNothing); }, ); scenario('cancel release confirmation keeps e-stop without sending zero', ( t, c, r, tcp, ) async { await mountButton(t, c); await t.tap(find.byType(EmergencyStopButton)); await t.pump(); await confirmDialog(t); await t.tap(find.byType(EmergencyStopButton)); await t.pump(const Duration(milliseconds: 400)); await t.tap(find.byKey(const ValueKey('emergency-cancel'))); await t.pump(const Duration(milliseconds: 400)); expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]); expect(c.state.isEmergency, isTrue); expect(find.byType(EmergencyOverlay), findsOneWidget); }); scenario('changing target while confirming never sends to another vehicle', ( t, c, r, tcp, ) async { await mountButton(t, c); await t.tap(find.byType(EmergencyStopButton)); await t.pump(); c.clearTargetDevice(); await confirmDialog(t); expect(emergency.calls, isEmpty); }); }