339 lines
9.1 KiB
Dart
339 lines
9.1 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
|
|
|
import '../models/scan_record.dart';
|
|
import 'feedback_service.dart';
|
|
import 'storage_service.dart';
|
|
|
|
enum ConnectionStatus {
|
|
disconnected,
|
|
connecting,
|
|
connected,
|
|
error,
|
|
}
|
|
|
|
class ConnectionService extends ChangeNotifier {
|
|
String _ip = '';
|
|
int _port = 8765;
|
|
String _pin = '';
|
|
String _serverName = '';
|
|
String _suffix = 'enter'; // enter, tab, none
|
|
bool _continuousMode = false;
|
|
bool _vibrate = true;
|
|
bool _sound = true;
|
|
|
|
ConnectionStatus _status = ConnectionStatus.disconnected;
|
|
String _statusMessage = 'Non connesso';
|
|
WebSocketChannel? _channel;
|
|
StreamSubscription? _channelSub;
|
|
Timer? _reconnectTimer;
|
|
Timer? _pingTimer;
|
|
bool _intentionalDisconnect = false;
|
|
|
|
List<ScanRecord> _history = [];
|
|
ScanRecord? _lastScan;
|
|
|
|
String get ip => _ip;
|
|
int get port => _port;
|
|
String get pin => _pin;
|
|
String get serverName => _serverName.isNotEmpty ? _serverName : (_ip.isNotEmpty ? _ip : 'Nessun PC');
|
|
String get suffix => _suffix;
|
|
bool get continuousMode => _continuousMode;
|
|
bool get vibrate => _vibrate;
|
|
bool get sound => _sound;
|
|
ConnectionStatus get status => _status;
|
|
String get statusMessage => _statusMessage;
|
|
List<ScanRecord> get history => _history;
|
|
ScanRecord? get lastScan => _lastScan;
|
|
bool get isConnected => _status == ConnectionStatus.connected;
|
|
|
|
Future<void> initialize() async {
|
|
final settings = await StorageService.loadSettings();
|
|
_ip = settings['ip'] as String? ?? '';
|
|
_port = settings['port'] as int? ?? 8765;
|
|
_pin = settings['pin'] as String? ?? '';
|
|
_serverName = settings['serverName'] as String? ?? '';
|
|
_suffix = settings['suffix'] as String? ?? 'enter';
|
|
_continuousMode = settings['continuous'] as bool? ?? false;
|
|
_vibrate = settings['vibrate'] as bool? ?? true;
|
|
_sound = settings['sound'] as bool? ?? true;
|
|
|
|
_history = await StorageService.loadHistory();
|
|
if (_history.isNotEmpty) {
|
|
_lastScan = _history.first;
|
|
}
|
|
notifyListeners();
|
|
|
|
if (_ip.isNotEmpty) {
|
|
connect();
|
|
}
|
|
}
|
|
|
|
void setServer({
|
|
required String ip,
|
|
required int port,
|
|
required String pin,
|
|
String? serverName,
|
|
}) {
|
|
_ip = ip.trim();
|
|
_port = port;
|
|
_pin = pin.trim();
|
|
if (serverName != null && serverName.isNotEmpty) {
|
|
_serverName = serverName;
|
|
}
|
|
StorageService.saveServerConnection(
|
|
ip: _ip,
|
|
port: _port,
|
|
pin: _pin,
|
|
serverName: _serverName,
|
|
);
|
|
notifyListeners();
|
|
connect();
|
|
}
|
|
|
|
void setSuffix(String suffix) {
|
|
_suffix = suffix;
|
|
StorageService.saveSuffix(suffix);
|
|
notifyListeners();
|
|
}
|
|
|
|
void setContinuousMode(bool enabled) {
|
|
_continuousMode = enabled;
|
|
StorageService.saveContinuousMode(enabled);
|
|
notifyListeners();
|
|
}
|
|
|
|
void setFeedbackToggles({required bool vibrate, required bool sound}) {
|
|
_vibrate = vibrate;
|
|
_sound = sound;
|
|
StorageService.saveFeedbackToggles(vibrate: vibrate, sound: sound);
|
|
notifyListeners();
|
|
}
|
|
|
|
Future<void> connect() async {
|
|
if (_ip.isEmpty) {
|
|
_status = ConnectionStatus.disconnected;
|
|
_statusMessage = 'Indirizzo IP non impostato';
|
|
notifyListeners();
|
|
return;
|
|
}
|
|
|
|
_intentionalDisconnect = false;
|
|
_reconnectTimer?.cancel();
|
|
_pingTimer?.cancel();
|
|
_closeChannel();
|
|
|
|
_status = ConnectionStatus.connecting;
|
|
_statusMessage = 'Connessione a $_ip:$_port in corso...';
|
|
notifyListeners();
|
|
|
|
try {
|
|
final wsUrl = Uri.parse('ws://$_ip:$_port/ws');
|
|
_channel = WebSocketChannel.connect(wsUrl);
|
|
|
|
// Timeout connection check via HTTP ping first or await channel stream
|
|
_channelSub = _channel!.stream.listen(
|
|
(data) {
|
|
_handleIncomingMessage(data);
|
|
},
|
|
onError: (err) {
|
|
_onConnectionError('Errore di connessione: $err');
|
|
},
|
|
onDone: () {
|
|
_onConnectionClosed();
|
|
},
|
|
cancelOnError: true,
|
|
);
|
|
|
|
// Handshake
|
|
final deviceName = Platform.isAndroid ? 'Android' : (Platform.isIOS ? 'iPhone' : 'Dispositivo Mobile');
|
|
_channel!.sink.add(jsonEncode({
|
|
'type': 'handshake',
|
|
'device_name': deviceName,
|
|
'pin': _pin,
|
|
}));
|
|
|
|
_status = ConnectionStatus.connected;
|
|
_statusMessage = 'Connesso a $_serverName ($_ip)';
|
|
notifyListeners();
|
|
|
|
_startPingLoop();
|
|
} catch (e) {
|
|
_onConnectionError('Impossibile connettersi: $e');
|
|
}
|
|
}
|
|
|
|
void disconnect() {
|
|
_intentionalDisconnect = true;
|
|
_reconnectTimer?.cancel();
|
|
_pingTimer?.cancel();
|
|
_closeChannel();
|
|
_status = ConnectionStatus.disconnected;
|
|
_statusMessage = 'Disconnesso manualmente';
|
|
notifyListeners();
|
|
}
|
|
|
|
void _closeChannel() {
|
|
_channelSub?.cancel();
|
|
_channelSub = null;
|
|
try {
|
|
_channel?.sink.close();
|
|
} catch (_) {}
|
|
_channel = null;
|
|
}
|
|
|
|
void _onConnectionError(String msg) {
|
|
_status = ConnectionStatus.error;
|
|
_statusMessage = msg;
|
|
_closeChannel();
|
|
notifyListeners();
|
|
_scheduleReconnect();
|
|
}
|
|
|
|
void _onConnectionClosed() {
|
|
if (_intentionalDisconnect) {
|
|
_status = ConnectionStatus.disconnected;
|
|
_statusMessage = 'Disconnesso';
|
|
} else {
|
|
_status = ConnectionStatus.disconnected;
|
|
_statusMessage = 'Connessione interrotta. Nuovo tentativo...';
|
|
_scheduleReconnect();
|
|
}
|
|
_closeChannel();
|
|
notifyListeners();
|
|
}
|
|
|
|
void _scheduleReconnect() {
|
|
if (_intentionalDisconnect || _ip.isEmpty) return;
|
|
_reconnectTimer?.cancel();
|
|
_reconnectTimer = Timer(const Duration(seconds: 4), () {
|
|
if (!_intentionalDisconnect && _status != ConnectionStatus.connected) {
|
|
connect();
|
|
}
|
|
});
|
|
}
|
|
|
|
void _startPingLoop() {
|
|
_pingTimer?.cancel();
|
|
_pingTimer = Timer.periodic(const Duration(seconds: 15), (t) {
|
|
if (_status == ConnectionStatus.connected && _channel != null) {
|
|
try {
|
|
_channel!.sink.add(jsonEncode({'type': 'ping'}));
|
|
} catch (_) {}
|
|
}
|
|
});
|
|
}
|
|
|
|
void _handleIncomingMessage(dynamic raw) {
|
|
try {
|
|
final json = jsonDecode(raw.toString()) as Map<String, dynamic>;
|
|
final type = json['type'] as String?;
|
|
|
|
if (type == 'welcome') {
|
|
if (json['server_name'] != null) {
|
|
_serverName = json['server_name'] as String;
|
|
StorageService.saveServerConnection(ip: _ip, port: _port, pin: _pin, serverName: _serverName);
|
|
}
|
|
_status = ConnectionStatus.connected;
|
|
_statusMessage = 'Connesso a $_serverName';
|
|
notifyListeners();
|
|
} else if (type == 'auth_error') {
|
|
_status = ConnectionStatus.error;
|
|
_statusMessage = 'Errore di autenticazione: PIN errato';
|
|
_intentionalDisconnect = true;
|
|
_closeChannel();
|
|
notifyListeners();
|
|
} else if (type == 'ack') {
|
|
FeedbackService.triggerSuccess();
|
|
}
|
|
} catch (_) {}
|
|
}
|
|
|
|
/// Invia un codice scansionato al PC (tramite WebSocket con fallback HTTP REST)
|
|
Future<bool> sendCode(String code, {String format = 'Barcode'}) async {
|
|
final cleanCode = code.trim();
|
|
if (cleanCode.isEmpty) return false;
|
|
|
|
// Trigger visual and haptic feedback
|
|
await FeedbackService.triggerFeedback(sound: _sound, vibrate: _vibrate);
|
|
|
|
bool success = false;
|
|
|
|
// 1. Prova tramite WebSocket se connesso
|
|
if (_status == ConnectionStatus.connected && _channel != null) {
|
|
try {
|
|
_channel!.sink.add(jsonEncode({
|
|
'type': 'scan',
|
|
'code': cleanCode,
|
|
'suffix': _suffix,
|
|
'pin': _pin,
|
|
}));
|
|
success = true;
|
|
} catch (_) {
|
|
success = false;
|
|
}
|
|
}
|
|
|
|
// 2. Se WebSocket non è riuscito o non connesso, fallback su HTTP POST
|
|
if (!success && _ip.isNotEmpty) {
|
|
try {
|
|
final uri = Uri.parse('http://$_ip:$_port/api/type');
|
|
final res = await http.post(
|
|
uri,
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({
|
|
'code': cleanCode,
|
|
'suffix': _suffix,
|
|
'pin': _pin,
|
|
'source': Platform.isAndroid ? 'Android (HTTP)' : 'iOS (HTTP)',
|
|
}),
|
|
).timeout(const Duration(seconds: 2));
|
|
|
|
if (res.statusCode == 200) {
|
|
success = true;
|
|
}
|
|
} catch (_) {
|
|
success = false;
|
|
}
|
|
}
|
|
|
|
final record = ScanRecord(
|
|
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
|
code: cleanCode,
|
|
format: format,
|
|
timestamp: DateTime.now(),
|
|
sentSuccessfully: success,
|
|
);
|
|
|
|
_lastScan = record;
|
|
_history.insert(0, record);
|
|
if (_history.length > 200) {
|
|
_history.removeRange(200, _history.length);
|
|
}
|
|
await StorageService.addHistoryItem(record);
|
|
|
|
notifyListeners();
|
|
return success;
|
|
}
|
|
|
|
Future<void> clearHistory() async {
|
|
_history.clear();
|
|
_lastScan = null;
|
|
await StorageService.clearHistory();
|
|
notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_intentionalDisconnect = true;
|
|
_reconnectTimer?.cancel();
|
|
_pingTimer?.cancel();
|
|
_closeChannel();
|
|
super.dispose();
|
|
}
|
|
}
|