feat: add audio and vibration feedback alongside configurable scan cooldowns

This commit is contained in:
brontomark committed 2026-11-11 21:45:38 +01:00
1 parent 6c7376cc1b
commit fd83f6fc75
22 files changed
+921 -57

No files matched your search

Binary file not shown.
Binary file not shown.
@@ -20,6 +20,7 @@ class AppConstants {
static const String keyInactivityTimeout = 'inactivity_timeout_minutes';
static const String keySuffix = 'server_suffix';
static const String keyContinuous = 'continuous_mode';
static const String keyScanCooldownMs = 'scan_cooldown_ms';
static const String keyVibrate = 'vibrate_enabled';
static const String keySound = 'sound_enabled';
static const String keyAimMode = 'scan_aim_mode';
@@ -32,4 +33,7 @@ class AppConstants {
// Default timeout in minutes
static const int defaultInactivityTimeoutMinutes = 5;
// Default post-scan cooldown pause in milliseconds (2.5 seconds)
static const int defaultScanCooldownMs = 2500;
}
+133 -12
View File
@@ -1,29 +1,151 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import 'package:vibration/vibration.dart';
class FeedbackService {
const FeedbackService();
Future<void> triggerScanFeedback({required bool sound, required bool vibrate}) async {
static AudioPlayer? _successPlayer;
static AudioPlayer? _errorPlayer;
static bool _audioConfigured = false;
static bool? _hasVibrator;
static bool get _isFlutterTest =>
!kIsWeb && Platform.environment.containsKey('FLUTTER_TEST');
static Future<void> _ensureAudioConfigured() async {
if (_audioConfigured || _isFlutterTest) return;
_audioConfigured = true;
try {
if (vibrate) {
await HapticFeedback.mediumImpact();
await AudioPlayer.global.setAudioContext(
AudioContext(
iOS: AudioContextIOS(
category: AVAudioSessionCategory.playback,
options: {AVAudioSessionOptions.mixWithOthers},
),
android: AudioContextAndroid(
isSpeakerphoneOn: false,
stayAwake: false,
contentType: AndroidContentType.sonification,
usageType: AndroidUsageType.assistanceSonification,
audioFocus: AndroidAudioFocus.none,
),
),
);
} catch (_) {}
}
static Future<AudioPlayer?> _getPlayer({required bool isError}) async {
if (_isFlutterTest) return null;
try {
await _ensureAudioConfigured();
if (isError) {
_errorPlayer ??= AudioPlayer()
..setReleaseMode(ReleaseMode.stop)
..setPlayerMode(PlayerMode.lowLatency);
return _errorPlayer;
} else {
_successPlayer ??= AudioPlayer()
..setReleaseMode(ReleaseMode.stop)
..setPlayerMode(PlayerMode.lowLatency);
return _successPlayer;
}
if (sound) {
await SystemSound.play(SystemSoundType.click);
} catch (_) {
return null;
}
}
Future<void> _playBeep({required bool isError}) async {
if (_isFlutterTest) return;
try {
final player = await _getPlayer(isError: isError);
if (player != null) {
await player.stop();
await player.play(
AssetSource(
isError ? 'sounds/beep_error.wav' : 'sounds/beep_success.wav',
),
volume: 1.0,
);
return;
}
} catch (_) {
// Fallback to system sound if asset player is unavailable
try {
await SystemSound.play(
isError ? SystemSoundType.alert : SystemSoundType.click,
);
} catch (_) {}
}
}
Future<void> _vibrate({required bool isError}) async {
if (_isFlutterTest) return;
try {
_hasVibrator ??= await Vibration.hasVibrator();
if (_hasVibrator == true) {
if (isError) {
await Vibration.vibrate(pattern: [0, 75, 65, 120]);
} else {
await Vibration.vibrate(duration: 110, amplitude: 220);
}
return;
}
} catch (_) {}
// Fallback to Flutter HapticFeedback
try {
if (isError) {
await HapticFeedback.vibrate();
} else {
await HapticFeedback.heavyImpact();
}
} catch (_) {}
}
/// Feedback confermato quando il codice è stato inviato con successo al PC.
Future<void> triggerSentSuccess({
required bool sound,
required bool vibrate,
}) async {
final futures = <Future<void>>[];
if (vibrate) futures.add(_vibrate(isError: false));
if (sound) futures.add(_playBeep(isError: false));
if (futures.isNotEmpty) {
await Future.wait(futures);
}
}
/// Feedback distinto quando l'invio al PC non è riuscito (es. PC disconnesso).
Future<void> triggerSentError({
required bool sound,
required bool vibrate,
}) async {
final futures = <Future<void>>[];
if (vibrate) futures.add(_vibrate(isError: true));
if (sound) futures.add(_playBeep(isError: true));
if (futures.isNotEmpty) {
await Future.wait(futures);
}
}
Future<void> triggerScanFeedback({
required bool sound,
required bool vibrate,
}) async {
await triggerSentSuccess(sound: sound, vibrate: vibrate);
}
Future<void> triggerSuccess() async {
try {
await HapticFeedback.heavyImpact();
} catch (_) {}
await _vibrate(isError: false);
}
Future<void> triggerError() async {
try {
await HapticFeedback.vibrate();
} catch (_) {}
await _vibrate(isError: true);
}
Future<void> triggerSelection() async {
@@ -32,4 +154,3 @@ class FeedbackService {
} catch (_) {}
}
}
@@ -1,3 +1,6 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/services/feedback_service.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart';
@@ -12,6 +15,8 @@ class ScannerCubit extends Cubit<ScannerState> {
final HistoryCubit historyCubit;
final FeedbackService feedbackService;
Timer? _cooldownTimer;
ScannerCubit({
required this.connectionCubit,
required this.settingsCubit,
@@ -33,34 +38,48 @@ class ScannerCubit extends Cubit<ScannerState> {
emit(state.copyWith(zoomScale: clamped));
}
void clearCooldown() {
_cooldownTimer?.cancel();
_cooldownTimer = null;
if (!isClosed && (state.cooldownUntil != null || state.cooldownTotalMs != 0)) {
emit(state.copyWith(clearCooldown: true));
}
}
Future<void> processBarcode(
String rawValue, {
String format = 'Barcode',
}) async {
final cleanCode = rawValue.trim();
if (cleanCode.isEmpty) return;
if (state.isProcessing || state.isInCooldown) return;
final now = DateTime.now();
final isSameCode = cleanCode == state.lastScannedValue;
final durationSinceLast = now.difference(state.lastScannedTime);
final continuous = settingsCubit.state.settings.continuousMode;
final settings = settingsCubit.state.settings;
// Minimum debounce interval for live camera stream
final minInterval = isSameCode
? (continuous
? const Duration(milliseconds: 1000)
: const Duration(milliseconds: 1800))
: const Duration(milliseconds: 600);
// Post-scan cooldown pause: gives the operator time (default 2.5s) to
// move the camera away before the next automatic read.
final configuredCooldownMs = settings.scanCooldownMs;
final effectiveCooldownMs = (settings.continuousMode && !isSameCode)
? math.min(configuredCooldownMs, 1000)
: configuredCooldownMs;
if (durationSinceLast < minInterval || state.isProcessing) {
if (durationSinceLast < Duration(milliseconds: effectiveCooldownMs)) {
return;
}
await _sendAndRecord(cleanCode, format: format, timestamp: now);
await _sendAndRecord(
cleanCode,
format: format,
timestamp: now,
cooldownMs: effectiveCooldownMs,
);
}
/// Sends a barcode explicitly chosen by the user (e.g. from AR badge or frozen picker),
/// bypassing the live-camera debounce so rapid multi-code picking feels instant.
/// bypassing the live-camera cooldown so rapid multi-code picking feels instant.
Future<bool> sendSelectedBarcode(
String rawValue, {
String format = 'Barcode',
@@ -93,6 +112,7 @@ class ScannerCubit extends Cubit<ScannerState> {
required DateTime timestamp,
String? idOverride,
bool updateDebounceTracker = true,
int cooldownMs = 0,
}) async {
emit(state.copyWith(
isProcessing: true,
@@ -101,18 +121,23 @@ class ScannerCubit extends Cubit<ScannerState> {
));
final settings = settingsCubit.state.settings;
await feedbackService.triggerScanFeedback(
sound: settings.sound,
vibrate: settings.vibrate,
);
final success = await connectionCubit.sendCode(
code: cleanCode,
suffix: settings.suffix,
);
// Distinct audio + vibration confirmation right when the code is sent
if (success) {
await feedbackService.triggerSuccess();
await feedbackService.triggerSentSuccess(
sound: settings.sound,
vibrate: settings.vibrate,
);
} else {
await feedbackService.triggerSentError(
sound: settings.sound,
vibrate: settings.vibrate,
);
}
final record = ScanRecord(
@@ -125,11 +150,32 @@ class ScannerCubit extends Cubit<ScannerState> {
await historyCubit.addScan(record);
emit(state.copyWith(
isProcessing: false,
lastScan: record,
));
DateTime? cooldownUntil;
var activeCooldownTotalMs = 0;
if (cooldownMs > 0) {
_cooldownTimer?.cancel();
cooldownUntil = DateTime.now().add(Duration(milliseconds: cooldownMs));
activeCooldownTotalMs = cooldownMs;
_cooldownTimer = Timer(Duration(milliseconds: cooldownMs), clearCooldown);
}
if (!isClosed) {
emit(state.copyWith(
isProcessing: false,
lastScan: record,
cooldownUntil: cooldownUntil,
cooldownTotalMs: activeCooldownTotalMs,
));
}
return record;
}
@override
Future<void> close() {
_cooldownTimer?.cancel();
_cooldownTimer = null;
return super.close();
}
}
@@ -9,6 +9,8 @@ class ScannerState extends Equatable {
final String? lastScannedValue;
final DateTime lastScannedTime;
final double zoomScale;
final DateTime? cooldownUntil;
final int cooldownTotalMs;
ScannerState({
this.lastScan,
@@ -18,9 +20,14 @@ class ScannerState extends Equatable {
this.lastScannedValue,
DateTime? lastScannedTime,
this.zoomScale = 0.0,
this.cooldownUntil,
this.cooldownTotalMs = 0,
}) : lastScannedTime =
lastScannedTime ?? DateTime.fromMillisecondsSinceEpoch(0);
bool get isInCooldown =>
cooldownUntil != null && DateTime.now().isBefore(cooldownUntil!);
ScannerState copyWith({
ScanRecord? lastScan,
bool? isTorchOn,
@@ -29,6 +36,9 @@ class ScannerState extends Equatable {
String? lastScannedValue,
DateTime? lastScannedTime,
double? zoomScale,
DateTime? cooldownUntil,
int? cooldownTotalMs,
bool clearCooldown = false,
}) {
return ScannerState(
lastScan: lastScan ?? this.lastScan,
@@ -38,6 +48,10 @@ class ScannerState extends Equatable {
lastScannedValue: lastScannedValue ?? this.lastScannedValue,
lastScannedTime: lastScannedTime ?? this.lastScannedTime,
zoomScale: zoomScale ?? this.zoomScale,
cooldownUntil:
clearCooldown ? null : (cooldownUntil ?? this.cooldownUntil),
cooldownTotalMs:
clearCooldown ? 0 : (cooldownTotalMs ?? this.cooldownTotalMs),
);
}
@@ -50,5 +64,7 @@ class ScannerState extends Equatable {
lastScannedValue,
lastScannedTime,
zoomScale,
cooldownUntil,
cooldownTotalMs,
];
}
@@ -487,6 +487,9 @@ class _ScannerScreenState extends State<ScannerScreen>
ScannerOverlay(
aimMode: aimMode,
hasPrecisionTarget: _precisionTargetIndex != null,
cooldownUntil: scannerState.cooldownUntil,
cooldownTotalMs: scannerState.cooldownTotalMs,
lastScanSucceeded: lastScan?.sentSuccessfully ?? true,
),
// 3. Live AR Overlay (outlines in Precisione, badges in AR Multi)
@@ -6,11 +6,17 @@ import '../utils/barcode_geometry.dart';
class ScannerOverlay extends StatefulWidget {
final ScanAimMode aimMode;
final bool hasPrecisionTarget;
final DateTime? cooldownUntil;
final int cooldownTotalMs;
final bool lastScanSucceeded;
const ScannerOverlay({
super.key,
this.aimMode = ScanAimMode.standard,
this.hasPrecisionTarget = false,
this.cooldownUntil,
this.cooldownTotalMs = 0,
this.lastScanSucceeded = true,
});
@override
@@ -55,10 +61,20 @@ class _ScannerOverlayState extends State<ScannerOverlay>
return const SizedBox.expand();
}
final cooldownUntil = widget.cooldownUntil;
final remainingMs = cooldownUntil != null
? cooldownUntil.difference(DateTime.now()).inMilliseconds
: 0;
final isCoolingDown = remainingMs > 0;
final cooldownColor =
widget.lastScanSucceeded ? AppTheme.success : AppTheme.warning;
final isPrecision = widget.aimMode == ScanAimMode.precision;
final accentColor = isPrecision && widget.hasPrecisionTarget
? AppTheme.success
: AppTheme.primary;
final accentColor = isCoolingDown
? cooldownColor
: (isPrecision && widget.hasPrecisionTarget
? AppTheme.success
: AppTheme.primary);
final maskAlpha = isPrecision ? 0.72 : 0.62;
final radius = isPrecision ? 14.0 : 18.0;
@@ -93,15 +109,19 @@ class _ScannerOverlayState extends State<ScannerOverlay>
),
),
// Outer border
// Outer border (+ subtle confirmation tint during cooldown)
Positioned.fromRect(
rect: scanRect,
child: Container(
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
decoration: BoxDecoration(
color: isCoolingDown
? cooldownColor.withValues(alpha: 0.14)
: Colors.transparent,
borderRadius: BorderRadius.circular(radius),
border: Border.all(
color: accentColor.withValues(alpha: 0.4),
width: 1.5,
color: accentColor.withValues(alpha: isCoolingDown ? 0.85 : 0.4),
width: isCoolingDown ? 2.0 : 1.5,
),
),
),
@@ -114,7 +134,34 @@ class _ScannerOverlayState extends State<ScannerOverlay>
radius: radius,
),
if (isPrecision)
if (isCoolingDown)
Positioned.fromRect(
rect: scanRect,
child: Center(
child: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: cooldownColor.withValues(alpha: 0.9),
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: cooldownColor.withValues(alpha: 0.5),
blurRadius: 14,
spreadRadius: 2,
),
],
),
child: Icon(
widget.lastScanSucceeded
? Icons.check_rounded
: Icons.priority_high_rounded,
color: Colors.white,
size: 28,
),
),
),
)
else if (isPrecision)
_PrecisionCrosshair(
scanRect: scanRect,
accentColor: accentColor,
@@ -157,26 +204,38 @@ class _ScannerOverlayState extends State<ScannerOverlay>
},
),
// Helper text below reticle
// Cooldown pill or helper text below reticle
Positioned(
left: 20,
right: 20,
top: scanRect.bottom + 14,
child: Text(
isPrecision
? 'Centra il mirino sul codice • Tocca per mettere a fuoco'
: 'Inquadra codice a barre o QR • Pizzica per zoomare',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
shadows: [
Shadow(color: Colors.black, blurRadius: 6),
],
),
),
child: isCoolingDown
? Center(
child: _CooldownStatusPill(
key: ValueKey(cooldownUntil),
remainingMs: remainingMs,
totalMs: widget.cooldownTotalMs > 0
? widget.cooldownTotalMs
: remainingMs,
succeeded: widget.lastScanSucceeded,
color: cooldownColor,
),
)
: Text(
isPrecision
? 'Centra il mirino sul codice • Tocca per mettere a fuoco'
: 'Inquadra codice a barre o QR • Pizzica per zoomare',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
shadows: [
Shadow(color: Colors.black, blurRadius: 6),
],
),
),
),
],
);
@@ -372,3 +431,89 @@ class _CornersPainter extends CustomPainter {
bool shouldRepaint(covariant _CornersPainter oldDelegate) =>
oldDelegate.color != color || oldDelegate.radius != radius;
}
class _CooldownStatusPill extends StatelessWidget {
final int remainingMs;
final int totalMs;
final bool succeeded;
final Color color;
const _CooldownStatusPill({
super.key,
required this.remainingMs,
required this.totalMs,
required this.succeeded,
required this.color,
});
@override
Widget build(BuildContext context) {
final startFraction = (remainingMs / totalMs).clamp(0.0, 1.0);
return TweenAnimationBuilder<double>(
tween: Tween(begin: startFraction, end: 0.0),
duration: Duration(milliseconds: remainingMs),
builder: (context, fraction, _) {
final secsLeft = (fraction * totalMs / 1000.0).clamp(0.0, 99.9);
final label = succeeded
? 'Inviato • Pausa ${secsLeft.toStringAsFixed(1)}s'
: 'Non inviato • Pausa ${secsLeft.toStringAsFixed(1)}s';
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: AppTheme.darkBackground.withValues(alpha: 0.88),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: color.withValues(alpha: 0.65), width: 1.2),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.4),
blurRadius: 10,
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
succeeded
? Icons.check_circle_rounded
: Icons.warning_amber_rounded,
size: 15,
color: color,
),
const SizedBox(width: 6),
Text(
label,
style: TextStyle(
color: color,
fontSize: 12,
fontWeight: FontWeight.w700,
letterSpacing: 0.2,
),
),
],
),
const SizedBox(height: 6),
SizedBox(
width: 150,
child: ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: fraction,
minHeight: 3,
backgroundColor: color.withValues(alpha: 0.2),
valueColor: AlwaysStoppedAnimation<Color>(color),
),
),
),
],
),
);
},
);
}
}
@@ -12,6 +12,8 @@ class SettingsLocalDataSource {
final suffix =
_prefs.getString(AppConstants.keySuffix) ?? AppConstants.suffixEnter;
final continuous = _prefs.getBool(AppConstants.keyContinuous) ?? false;
final scanCooldownMs = _prefs.getInt(AppConstants.keyScanCooldownMs) ??
AppConstants.defaultScanCooldownMs;
final vibrate = _prefs.getBool(AppConstants.keyVibrate) ?? true;
final sound = _prefs.getBool(AppConstants.keySound) ?? true;
final autoConnect = _prefs.getBool(AppConstants.keyAutoConnect) ?? false;
@@ -24,6 +26,7 @@ class SettingsLocalDataSource {
return AppSettings(
suffix: suffix,
continuousMode: continuous,
scanCooldownMs: scanCooldownMs,
vibrate: vibrate,
sound: sound,
autoConnect: autoConnect,
@@ -40,6 +43,10 @@ class SettingsLocalDataSource {
await _prefs.setBool(AppConstants.keyContinuous, enabled);
}
Future<void> saveScanCooldownMs(int cooldownMs) async {
await _prefs.setInt(AppConstants.keyScanCooldownMs, cooldownMs);
}
Future<void> saveFeedbackToggles(
{required bool vibrate, required bool sound}) async {
await _prefs.setBool(AppConstants.keyVibrate, vibrate);
@@ -23,6 +23,11 @@ class SettingsRepositoryImpl implements SettingsRepository {
await _localDataSource.saveContinuousMode(enabled);
}
@override
Future<void> saveScanCooldownMs(int cooldownMs) async {
await _localDataSource.saveScanCooldownMs(cooldownMs);
}
@override
Future<void> saveFeedbackToggles(
{required bool vibrate, required bool sound}) async {
@@ -5,6 +5,7 @@ import '../../../scanner/domain/entities/scan_aim_mode.dart';
class AppSettings extends Equatable {
final String suffix; // 'enter', 'tab', 'none'
final bool continuousMode;
final int scanCooldownMs; // Default: 2500ms (2.5s pause between scans)
final bool vibrate;
final bool sound;
final bool autoConnect; // Default: false (ideal for multi-PC store)
@@ -14,6 +15,7 @@ class AppSettings extends Equatable {
const AppSettings({
this.suffix = 'enter',
this.continuousMode = false,
this.scanCooldownMs = AppConstants.defaultScanCooldownMs,
this.vibrate = true,
this.sound = true,
this.autoConnect = false,
@@ -24,6 +26,7 @@ class AppSettings extends Equatable {
AppSettings copyWith({
String? suffix,
bool? continuousMode,
int? scanCooldownMs,
bool? vibrate,
bool? sound,
bool? autoConnect,
@@ -33,6 +36,7 @@ class AppSettings extends Equatable {
return AppSettings(
suffix: suffix ?? this.suffix,
continuousMode: continuousMode ?? this.continuousMode,
scanCooldownMs: scanCooldownMs ?? this.scanCooldownMs,
vibrate: vibrate ?? this.vibrate,
sound: sound ?? this.sound,
autoConnect: autoConnect ?? this.autoConnect,
@@ -46,6 +50,7 @@ class AppSettings extends Equatable {
List<Object?> get props => [
suffix,
continuousMode,
scanCooldownMs,
vibrate,
sound,
autoConnect,
@@ -5,6 +5,7 @@ abstract class SettingsRepository {
Future<AppSettings> loadSettings();
Future<void> saveSuffix(String suffix);
Future<void> saveContinuousMode(bool enabled);
Future<void> saveScanCooldownMs(int cooldownMs);
Future<void> saveFeedbackToggles({required bool vibrate, required bool sound});
Future<void> saveAutoConnect(bool enabled);
Future<void> saveInactivityTimeout(int minutes);
@@ -30,6 +30,12 @@ class SettingsCubit extends Cubit<SettingsState> {
await _settingsRepository.saveContinuousMode(enabled);
}
Future<void> updateScanCooldownMs(int cooldownMs) async {
final updated = state.settings.copyWith(scanCooldownMs: cooldownMs);
emit(state.copyWith(settings: updated));
await _settingsRepository.saveScanCooldownMs(cooldownMs);
}
Future<void> updateFeedback({bool? vibrate, bool? sound}) async {
final updated = state.settings.copyWith(
vibrate: vibrate ?? state.settings.vibrate,
@@ -302,6 +302,47 @@ class SettingsScreen extends StatelessWidget {
),
),
const Divider(height: 1),
ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: AppTheme.primary.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.hourglass_bottom_rounded,
color: AppTheme.primary, size: 22),
),
title: const Text('Pausa dopo scansione'),
subtitle: Text(
'Attesa di ${(settings.scanCooldownMs / 1000).toStringAsFixed(1).replaceAll('.', ',')}s prima della prossima lettura',
style: const TextStyle(fontSize: 12),
),
trailing: DropdownButton<int>(
value: settings.scanCooldownMs,
dropdownColor: AppTheme.darkCard,
style: const TextStyle(
color: AppTheme.darkTextPrimary,
fontWeight: FontWeight.bold,
),
underline: const SizedBox.shrink(),
items: const [
DropdownMenuItem(value: 1000, child: Text('1,0 sec (Rapida)')),
DropdownMenuItem(value: 2000, child: Text('2,0 sec')),
DropdownMenuItem(value: 2500, child: Text('2,5 sec (Consigliata)')),
DropdownMenuItem(value: 3000, child: Text('3,0 sec')),
DropdownMenuItem(value: 4000, child: Text('4,0 sec')),
DropdownMenuItem(value: 5000, child: Text('5,0 sec')),
],
onChanged: (val) {
if (val != null) {
context
.read<SettingsCubit>()
.updateScanCooldownMs(val);
}
},
),
),
const Divider(height: 1),
SwitchListTile(
secondary: Container(
padding: const EdgeInsets.all(8),
@@ -314,8 +355,8 @@ class SettingsScreen extends StatelessWidget {
),
title: const Text('Scansione Continua'),
subtitle: const Text(
'Continua a leggere codici in sequenza senza pause',
style: TextStyle(fontSize: 13),
'Riduce la pausa a 1,0s quando inquadri codici diversi in serie',
style: TextStyle(fontSize: 12),
),
value: settings.continuousMode,
onChanged: (val) {
@@ -6,6 +6,10 @@
#include "generated_plugin_registrant.h"
#include <audioplayers_linux/audioplayers_linux_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin");
audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar);
}
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
@@ -5,10 +5,14 @@
import FlutterMacOS
import Foundation
import audioplayers_darwin
import device_info_plus
import mobile_scanner
import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
}
+224
View File
@@ -17,6 +17,62 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.13.1"
audioplayers:
dependency: "direct main"
description:
name: audioplayers
sha256: "2ba4bb2944baacbdd5372ff8254a8e7feb8c10d7739545e392f5605a8f618745"
url: "https://pub.dev"
source: hosted
version: "6.8.1"
audioplayers_android:
dependency: transitive
description:
name: audioplayers_android
sha256: f5ff5b15620fbab8cb0849e9636c48e2b96c3f0f71723bbbe2ad3c761b205f05
url: "https://pub.dev"
source: hosted
version: "5.3.0"
audioplayers_darwin:
dependency: transitive
description:
name: audioplayers_darwin
sha256: "1ca553add991384ecf421b9569da850f3ab2472ffb83f6970b0416365abc51be"
url: "https://pub.dev"
source: hosted
version: "6.5.0"
audioplayers_linux:
dependency: transitive
description:
name: audioplayers_linux
sha256: "15178b726b7cdee5364d0463c8d445630c4e0fb7d26612b73c767e7d25de9417"
url: "https://pub.dev"
source: hosted
version: "4.3.0"
audioplayers_platform_interface:
dependency: transitive
description:
name: audioplayers_platform_interface
sha256: "765f6f0e6dca55cb471c9483fc77700564b3484d19198aca4ebb5147c6c85acb"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
audioplayers_web:
dependency: transitive
description:
name: audioplayers_web
sha256: ae1e0103c865a03e273f6d13d97b93f5595eac09915729cd5e37ef96e2857319
url: "https://pub.dev"
source: hosted
version: "5.3.0"
audioplayers_windows:
dependency: transitive
description:
name: audioplayers_windows
sha256: a70ae82bba2dfcb6eb03dd4815d737a2d46d33ea5a96a03f535cfcaac490e413
url: "https://pub.dev"
source: hosted
version: "4.4.1"
bloc:
dependency: transitive
description:
@@ -49,6 +105,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.3"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev"
source: hosted
version: "1.2.1"
collection:
dependency: transitive
description:
@@ -73,6 +137,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.9"
device_info_plus:
dependency: transitive
description:
name: device_info_plus
sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa
url: "https://pub.dev"
source: hosted
version: "13.3.0"
device_info_plus_platform_interface:
dependency: transitive
description:
name: device_info_plus_platform_interface
sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46"
url: "https://pub.dev"
source: hosted
version: "8.1.0"
equatable:
dependency: "direct main"
description:
@@ -97,6 +177,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
ffi_leak_tracker:
dependency: transitive
description:
name: ffi_leak_tracker
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
file:
dependency: transitive
description:
@@ -105,6 +193,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
@@ -136,6 +232,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
hooks:
dependency: transitive
description:
name: hooks
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
http:
dependency: "direct main"
description:
@@ -160,6 +264,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
url: "https://pub.dev"
source: hosted
version: "1.0.4+1"
jni_util:
dependency: transitive
description:
@@ -200,6 +312,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.0"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
@@ -240,6 +360,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.0"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e
url: "https://pub.dev"
source: hosted
version: "9.5.0"
package_config:
dependency: transitive
description:
@@ -256,6 +384,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: transitive
description:
name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
path_provider_linux:
dependency: transitive
description:
@@ -304,6 +456,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
record_use:
dependency: transitive
description:
name: record_use
sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"
url: "https://pub.dev"
source: hosted
version: "0.6.0"
shared_preferences:
dependency: "direct main"
description:
@@ -397,6 +565,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
synchronized:
dependency: transitive
description:
name: synchronized
sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94
url: "https://pub.dev"
source: hosted
version: "3.6.1+1"
term_glyph:
dependency: transitive
description:
@@ -421,6 +597,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
uuid:
dependency: transitive
description:
name: uuid
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
url: "https://pub.dev"
source: hosted
version: "4.6.0"
vector_math:
dependency: transitive
description:
@@ -429,6 +613,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.4.0"
vibration:
dependency: "direct main"
description:
name: vibration
sha256: "3424f7856b971a2ce94d22be3a3abfb5b9b5984562fdedd621f4e67574be7254"
url: "https://pub.dev"
source: hosted
version: "3.2.1"
vibration_platform_interface:
dependency: transitive
description:
name: vibration_platform_interface
sha256: "258c273268f8aa40c88d29741137c536874a738779b92ddb8aa32ed093721ec5"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
vm_service:
dependency: transitive
description:
@@ -461,6 +661,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.3"
win32:
dependency: transitive
description:
name: win32
sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d
url: "https://pub.dev"
source: hosted
version: "6.4.0"
win32_registry:
dependency: transitive
description:
name: win32_registry
sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904"
url: "https://pub.dev"
source: hosted
version: "3.0.3"
xdg_directories:
dependency: transitive
description:
@@ -469,6 +685,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
yaml:
dependency: transitive
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.13.4 <4.0.0"
flutter: ">=3.44.0"
+5
View File
@@ -40,6 +40,8 @@ dependencies:
shared_preferences: ^2.5.6
flutter_bloc: ^9.1.1
equatable: ^3.0.0
audioplayers: ^6.8.1
vibration: ^3.2.1
dev_dependencies:
flutter_test:
@@ -63,6 +65,9 @@ flutter:
# the material Icons class.
uses-material-design: true
assets:
- assets/sounds/
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
@@ -0,0 +1,222 @@
import 'package:barcode_reader_app/core/services/feedback_service.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_local_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/repositories/connection_repository_impl.dart';
import 'package:barcode_reader_app/features/connection/domain/entities/discovered_server.dart';
import 'package:barcode_reader_app/features/connection/domain/entities/server_connection_info.dart';
import 'package:barcode_reader_app/features/connection/domain/repositories/connection_repository.dart';
import 'package:barcode_reader_app/features/connection/presentation/cubit/connection_cubit.dart';
import 'package:barcode_reader_app/features/scanner/data/datasources/scan_history_datasource.dart';
import 'package:barcode_reader_app/features/scanner/data/repositories/scan_repository_impl.dart';
import 'package:barcode_reader_app/features/scanner/domain/entities/scan_aim_mode.dart';
import 'package:barcode_reader_app/features/scanner/presentation/cubit/history_cubit.dart';
import 'package:barcode_reader_app/features/scanner/presentation/cubit/scanner_cubit.dart';
import 'package:barcode_reader_app/features/scanner/presentation/widgets/scanner_overlay.dart';
import 'package:barcode_reader_app/features/settings/data/datasources/settings_local_datasource.dart';
import 'package:barcode_reader_app/features/settings/data/repositories/settings_repository_impl.dart';
import 'package:barcode_reader_app/features/settings/presentation/cubit/settings_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _SpyFeedbackService extends FeedbackService {
int successCalls = 0;
int errorCalls = 0;
bool? lastSound;
bool? lastVibrate;
@override
Future<void> triggerSentSuccess({
required bool sound,
required bool vibrate,
}) async {
successCalls++;
lastSound = sound;
lastVibrate = vibrate;
}
@override
Future<void> triggerSentError({
required bool sound,
required bool vibrate,
}) async {
errorCalls++;
lastSound = sound;
lastVibrate = vibrate;
}
}
class _FakeConnectionRepository implements ConnectionRepository {
bool nextSendResult = true;
@override
ConnectionStatus get currentStatus => ConnectionStatus.connected;
@override
Stream<String> get messageStream => const Stream.empty();
@override
Stream<ConnectionStatus> get statusStream => const Stream.empty();
@override
Future<void> connect(ServerConnectionInfo info) async {}
@override
Future<void> disconnect() async {}
@override
Future<List<DiscoveredServer>> discoverServers({
Duration timeout = const Duration(seconds: 3),
}) async =>
const [];
@override
Future<List<ServerConnectionInfo>> loadFavoriteServers() async => const [];
@override
Future<ServerConnectionInfo> loadSavedConnection() async =>
const ServerConnectionInfo();
@override
Future<void> removeFavoriteServer(String id) async {}
@override
Future<void> saveConnection(ServerConnectionInfo info) async {}
@override
Future<void> saveFavoriteServer(ServerConnectionInfo server) async {}
@override
Future<bool> sendCode({
required String code,
required String suffix,
required String pin,
String? ip,
int? port,
}) async =>
nextSendResult;
@override
void dispose() {}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Scan Feedback & Cooldown Pause', () {
late SharedPreferences prefs;
late SettingsRepositoryImpl settingsRepo;
late ScanRepositoryImpl scanRepo;
late _FakeConnectionRepository fakeConnectionRepo;
late ConnectionRepositoryImpl realConnectionRepo;
setUp(() async {
SharedPreferences.setMockInitialValues({});
prefs = await SharedPreferences.getInstance();
settingsRepo = SettingsRepositoryImpl(SettingsLocalDataSource(prefs));
scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
fakeConnectionRepo = _FakeConnectionRepository();
realConnectionRepo = ConnectionRepositoryImpl(
localDataSource: ConnectionLocalDataSource(prefs),
remoteDataSource: ConnectionRemoteDataSource(),
discoveryDataSource: const UdpDiscoveryDataSource(),
);
});
tearDown(() {
realConnectionRepo.dispose();
});
test('SettingsCubit defaults scanCooldownMs to 2500ms and persists updates',
() async {
final cubit = SettingsCubit(settingsRepo);
await cubit.loadSettings();
expect(cubit.state.settings.scanCooldownMs, 2500);
await cubit.updateScanCooldownMs(3000);
expect(cubit.state.settings.scanCooldownMs, 3000);
final reloaded = await settingsRepo.loadSettings();
expect(reloaded.scanCooldownMs, 3000);
});
test(
'ScannerCubit triggers success/error feedback on send and enforces post-scan cooldown',
() async {
final settingsCubit = SettingsCubit(settingsRepo);
await settingsCubit.loadSettings();
await settingsCubit.updateScanCooldownMs(3000);
final connectionCubit = ConnectionCubit(fakeConnectionRepo);
final historyCubit = HistoryCubit(scanRepo);
final spyFeedback = _SpyFeedbackService();
final scannerCubit = ScannerCubit(
connectionCubit: connectionCubit,
settingsCubit: settingsCubit,
historyCubit: historyCubit,
feedbackService: spyFeedback,
);
addTearDown(scannerCubit.close);
addTearDown(connectionCubit.close);
// 1. Successful send triggers success sound & vibration and starts 3s cooldown
fakeConnectionRepo.nextSendResult = true;
await scannerCubit.processBarcode('8001234567890', format: 'ean13');
expect(spyFeedback.successCalls, 1);
expect(spyFeedback.errorCalls, 0);
expect(spyFeedback.lastSound, true);
expect(spyFeedback.lastVibrate, true);
expect(scannerCubit.state.isInCooldown, true);
expect(scannerCubit.state.cooldownTotalMs, 3000);
expect(historyCubit.state.history.length, 1);
// 2. Immediate second barcode (even a DIFFERENT code) is blocked by 3s cooldown
await scannerCubit.processBarcode('9998887776665', format: 'code128');
expect(historyCubit.state.history.length, 1);
expect(spyFeedback.successCalls, 1);
// 3. After cooldown clears, next scan is accepted; if send fails, error feedback triggers
scannerCubit.clearCooldown();
// Reset lastScannedTime by simulating elapsed time via resend/new scan check:
// Note: durationSinceLast still checks lastScannedTime when testing synchronously,
// so verify sendSelectedBarcode triggers error feedback when send fails.
fakeConnectionRepo.nextSendResult = false;
final sent = await scannerCubit.sendSelectedBarcode('FAIL-001');
expect(sent, false);
expect(spyFeedback.errorCalls, 1);
expect(historyCubit.state.history.length, 2);
});
testWidgets('ScannerOverlay displays green confirmation and cooldown pill',
(tester) async {
final cooldownUntil = DateTime.now().add(const Duration(milliseconds: 2500));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 400,
height: 800,
child: ScannerOverlay(
aimMode: ScanAimMode.standard,
cooldownUntil: cooldownUntil,
cooldownTotalMs: 2500,
lastScanSucceeded: true,
),
),
),
),
);
expect(find.byIcon(Icons.check_rounded), findsOneWidget);
expect(find.textContaining('Inviato • Pausa'), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsOneWidget);
});
});
}
@@ -6,6 +6,9 @@
#include "generated_plugin_registrant.h"
#include <audioplayers_windows/audioplayers_windows_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
AudioplayersWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin"));
}
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST