feat: add android multicast lock, network config, and connection ack handling
This commit is contained in:
1 parent
6a8729a147
commit
2d94be87ae
10 files changed
+344
-29
No files matched your search
@@ -56,6 +56,10 @@ android {
|
|||||||
} else {
|
} else {
|
||||||
signingConfigs.getByName("debug")
|
signingConfigs.getByName("debug")
|
||||||
}
|
}
|
||||||
|
proguardFiles(
|
||||||
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
|
"proguard-rules.pro"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+19
@@ -0,0 +1,19 @@
|
|||||||
|
# Flutter ProGuard Rules
|
||||||
|
-keep class io.flutter.app.** { *; }
|
||||||
|
-keep class io.flutter.plugin.** { *; }
|
||||||
|
-keep class io.flutter.util.** { *; }
|
||||||
|
-keep class io.flutter.view.** { *; }
|
||||||
|
-keep class io.flutter.** { *; }
|
||||||
|
-keep class io.flutter.plugins.** { *; }
|
||||||
|
|
||||||
|
# Flutter Play Core Deferred Components
|
||||||
|
-dontwarn com.google.android.play.core.**
|
||||||
|
|
||||||
|
# Keep MainActivity
|
||||||
|
-keep class com.catellisrl.barcode_reader_app.** { *; }
|
||||||
|
|
||||||
|
# Networking, Sockets & Wi-Fi
|
||||||
|
-keep class java.net.** { *; }
|
||||||
|
-keep class android.net.** { *; }
|
||||||
|
-keep class android.net.wifi.** { *; }
|
||||||
|
|
||||||
@@ -3,13 +3,15 @@
|
|||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||||
<uses-permission android:name="android.permission.VIBRATE" />
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:label="Barcode Reader"
|
android:label="Barcode Reader"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:usesCleartextTraffic="true">
|
android:usesCleartextTraffic="true"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config">
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
|||||||
@@ -1,5 +1,57 @@
|
|||||||
package com.catellisrl.barcode_reader_app
|
package com.catellisrl.barcode_reader_app
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.wifi.WifiManager
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
|
import io.flutter.plugin.common.MethodChannel
|
||||||
|
|
||||||
class MainActivity : FlutterActivity()
|
class MainActivity : FlutterActivity() {
|
||||||
|
private val CHANNEL = "com.catellisrl.barcode_reader/multicast"
|
||||||
|
private var multicastLock: WifiManager.MulticastLock? = null
|
||||||
|
|
||||||
|
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||||
|
super.configureFlutterEngine(flutterEngine)
|
||||||
|
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"acquireMulticastLock" -> {
|
||||||
|
try {
|
||||||
|
if (multicastLock == null) {
|
||||||
|
val wifi = applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||||
|
multicastLock = wifi?.createMulticastLock("barcode_reader_multicast_lock")?.apply {
|
||||||
|
setReferenceCounted(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (multicastLock?.isHeld == false) {
|
||||||
|
multicastLock?.acquire()
|
||||||
|
}
|
||||||
|
result.success(true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
result.error("LOCK_ERROR", e.message, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"releaseMulticastLock" -> {
|
||||||
|
try {
|
||||||
|
if (multicastLock?.isHeld == true) {
|
||||||
|
multicastLock?.release()
|
||||||
|
}
|
||||||
|
result.success(true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
result.error("LOCK_ERROR", e.message, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
try {
|
||||||
|
if (multicastLock?.isHeld == true) {
|
||||||
|
multicastLock?.release()
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {}
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<network-security-config>
|
||||||
|
<base-config cleartextTrafficPermitted="true">
|
||||||
|
<trust-anchors>
|
||||||
|
<certificates src="system" />
|
||||||
|
</trust-anchors>
|
||||||
|
</base-config>
|
||||||
|
</network-security-config>
|
||||||
|
|
||||||
@@ -18,6 +18,8 @@ class ConnectionRemoteDataSource {
|
|||||||
final StreamController<String> _serverNameController =
|
final StreamController<String> _serverNameController =
|
||||||
StreamController<String>.broadcast();
|
StreamController<String>.broadcast();
|
||||||
|
|
||||||
|
final Map<String, Completer<bool>> _pendingAcks = {};
|
||||||
|
|
||||||
ConnectionStatus _status = ConnectionStatus.disconnected;
|
ConnectionStatus _status = ConnectionStatus.disconnected;
|
||||||
|
|
||||||
Stream<ConnectionStatus> get statusStream => _statusController.stream;
|
Stream<ConnectionStatus> get statusStream => _statusController.stream;
|
||||||
@@ -80,9 +82,27 @@ class ConnectionRemoteDataSource {
|
|||||||
_serverNameController.add(serverName);
|
_serverNameController.add(serverName);
|
||||||
_setStatus(ConnectionStatus.connected, 'Connesso a $serverName');
|
_setStatus(ConnectionStatus.connected, 'Connesso a $serverName');
|
||||||
}
|
}
|
||||||
} else if (type == 'auth_error') {
|
} else if (type == 'ack') {
|
||||||
_setStatus(ConnectionStatus.error, 'PIN errato: autenticazione fallita');
|
final reqId = json['req_id'] as String?;
|
||||||
_disconnectInternal();
|
final success = json['success'] == true;
|
||||||
|
if (reqId != null && _pendingAcks.containsKey(reqId)) {
|
||||||
|
_pendingAcks.remove(reqId)?.complete(success);
|
||||||
|
} else if (_pendingAcks.isNotEmpty) {
|
||||||
|
final firstKey = _pendingAcks.keys.first;
|
||||||
|
_pendingAcks.remove(firstKey)?.complete(success);
|
||||||
|
}
|
||||||
|
} else if (type == 'paused' || type == 'auth_error' || type == 'error') {
|
||||||
|
final reqId = json['req_id'] as String?;
|
||||||
|
if (reqId != null && _pendingAcks.containsKey(reqId)) {
|
||||||
|
_pendingAcks.remove(reqId)?.complete(false);
|
||||||
|
} else if (_pendingAcks.isNotEmpty) {
|
||||||
|
final firstKey = _pendingAcks.keys.first;
|
||||||
|
_pendingAcks.remove(firstKey)?.complete(false);
|
||||||
|
}
|
||||||
|
if (type == 'auth_error') {
|
||||||
|
_setStatus(ConnectionStatus.error, 'PIN errato: autenticazione fallita');
|
||||||
|
_disconnectInternal();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
@@ -99,20 +119,36 @@ class ConnectionRemoteDataSource {
|
|||||||
|
|
||||||
// 1. Try WebSocket if connected
|
// 1. Try WebSocket if connected
|
||||||
if (_status == ConnectionStatus.connected && _channel != null) {
|
if (_status == ConnectionStatus.connected && _channel != null) {
|
||||||
|
final reqId = 'scan_${DateTime.now().microsecondsSinceEpoch}';
|
||||||
|
final completer = Completer<bool>();
|
||||||
|
_pendingAcks[reqId] = completer;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
_channel!.sink.add(jsonEncode({
|
_channel!.sink.add(jsonEncode({
|
||||||
'type': 'scan',
|
'type': 'scan',
|
||||||
'code': cleanCode,
|
'code': cleanCode,
|
||||||
'suffix': suffix,
|
'suffix': suffix,
|
||||||
'pin': pin,
|
'pin': pin,
|
||||||
|
'req_id': reqId,
|
||||||
}));
|
}));
|
||||||
return true;
|
|
||||||
|
final ackReceived = await completer.future.timeout(
|
||||||
|
const Duration(milliseconds: 1500),
|
||||||
|
onTimeout: () {
|
||||||
|
_pendingAcks.remove(reqId);
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ackReceived) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
// Fallback to HTTP
|
_pendingAcks.remove(reqId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. HTTP Fallback
|
// 2. HTTP Fallback if WebSocket not connected or failed/timed out
|
||||||
if (ip.isNotEmpty) {
|
if (ip.isNotEmpty) {
|
||||||
try {
|
try {
|
||||||
final uri = Uri.parse('http://$ip:$port/api/type');
|
final uri = Uri.parse('http://$ip:$port/api/type');
|
||||||
@@ -125,10 +161,13 @@ class ConnectionRemoteDataSource {
|
|||||||
'pin': pin,
|
'pin': pin,
|
||||||
'source': Platform.isAndroid ? 'Android (HTTP)' : 'iOS (HTTP)',
|
'source': Platform.isAndroid ? 'Android (HTTP)' : 'iOS (HTTP)',
|
||||||
}),
|
}),
|
||||||
).timeout(const Duration(seconds: 2));
|
).timeout(const Duration(milliseconds: 1500));
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
return true;
|
final body = jsonDecode(response.body);
|
||||||
|
if (body is Map && body['success'] == true) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return false;
|
return false;
|
||||||
@@ -148,6 +187,14 @@ class ConnectionRemoteDataSource {
|
|||||||
_pingTimer = null;
|
_pingTimer = null;
|
||||||
_channelSub?.cancel();
|
_channelSub?.cancel();
|
||||||
_channelSub = null;
|
_channelSub = null;
|
||||||
|
|
||||||
|
for (final completer in _pendingAcks.values) {
|
||||||
|
if (!completer.isCompleted) {
|
||||||
|
completer.complete(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_pendingAcks.clear();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
_channel?.sink.close();
|
_channel?.sink.close();
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
@@ -178,4 +225,3 @@ class ConnectionRemoteDataSource {
|
|||||||
_serverNameController.close();
|
_serverNameController.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
import '../../../../core/constants/app_constants.dart';
|
import '../../../../core/constants/app_constants.dart';
|
||||||
import '../../domain/entities/discovered_server.dart';
|
import '../../domain/entities/discovered_server.dart';
|
||||||
|
|
||||||
class UdpDiscoveryDataSource {
|
class UdpDiscoveryDataSource {
|
||||||
|
static const MethodChannel _multicastChannel =
|
||||||
|
MethodChannel('com.catellisrl.barcode_reader/multicast');
|
||||||
|
|
||||||
const UdpDiscoveryDataSource();
|
const UdpDiscoveryDataSource();
|
||||||
|
|
||||||
Future<List<DiscoveredServer>> discover({
|
Future<List<DiscoveredServer>> discover({
|
||||||
@@ -12,21 +16,71 @@ class UdpDiscoveryDataSource {
|
|||||||
}) async {
|
}) async {
|
||||||
final Map<String, DiscoveredServer> found = {};
|
final Map<String, DiscoveredServer> found = {};
|
||||||
RawDatagramSocket? socket;
|
RawDatagramSocket? socket;
|
||||||
|
StreamSubscription? sub;
|
||||||
|
Timer? pulseTimer1;
|
||||||
|
Timer? pulseTimer2;
|
||||||
|
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
try {
|
||||||
|
await _multicastChannel.invokeMethod('acquireMulticastLock');
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void cleanup() {
|
||||||
|
pulseTimer1?.cancel();
|
||||||
|
pulseTimer2?.cancel();
|
||||||
|
sub?.cancel();
|
||||||
|
socket?.close();
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
try {
|
||||||
|
_multicastChannel.invokeMethod('releaseMulticastLock');
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
|
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
|
||||||
socket.broadcastEnabled = true;
|
socket.broadcastEnabled = true;
|
||||||
|
|
||||||
final data = utf8.encode(AppConstants.udpDiscoveryMessage);
|
final data = utf8.encode(AppConstants.udpDiscoveryMessage);
|
||||||
socket.send(
|
|
||||||
data,
|
// Collect global broadcast and subnet-directed broadcast addresses
|
||||||
|
final broadcastTargets = <InternetAddress>{
|
||||||
InternetAddress('255.255.255.255'),
|
InternetAddress('255.255.255.255'),
|
||||||
AppConstants.defaultUdpDiscoveryPort,
|
};
|
||||||
);
|
|
||||||
|
try {
|
||||||
|
final interfaces = await NetworkInterface.list(
|
||||||
|
type: InternetAddressType.IPv4,
|
||||||
|
includeLoopback: false,
|
||||||
|
);
|
||||||
|
for (final iface in interfaces) {
|
||||||
|
for (final addr in iface.addresses) {
|
||||||
|
final parts = addr.address.split('.');
|
||||||
|
if (parts.length == 4) {
|
||||||
|
broadcastTargets.add(
|
||||||
|
InternetAddress('${parts[0]}.${parts[1]}.${parts[2]}.255'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
void sendPulse() {
|
||||||
|
for (final target in broadcastTargets) {
|
||||||
|
try {
|
||||||
|
socket?.send(data, target, AppConstants.defaultUdpDiscoveryPort);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendPulse();
|
||||||
|
pulseTimer1 = Timer(const Duration(milliseconds: 250), sendPulse);
|
||||||
|
pulseTimer2 = Timer(const Duration(milliseconds: 550), sendPulse);
|
||||||
|
|
||||||
final completer = Completer<List<DiscoveredServer>>();
|
final completer = Completer<List<DiscoveredServer>>();
|
||||||
|
|
||||||
final sub = socket.listen((event) {
|
sub = socket.listen((event) {
|
||||||
if (event == RawSocketEvent.read) {
|
if (event == RawSocketEvent.read) {
|
||||||
final datagram = socket?.receive();
|
final datagram = socket?.receive();
|
||||||
if (datagram != null) {
|
if (datagram != null) {
|
||||||
@@ -46,17 +100,15 @@ class UdpDiscoveryDataSource {
|
|||||||
|
|
||||||
Timer(timeout, () {
|
Timer(timeout, () {
|
||||||
if (!completer.isCompleted) {
|
if (!completer.isCompleted) {
|
||||||
sub.cancel();
|
cleanup();
|
||||||
socket?.close();
|
|
||||||
completer.complete(found.values.toList());
|
completer.complete(found.values.toList());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return await completer.future;
|
return await completer.future;
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
socket?.close();
|
cleanup();
|
||||||
return found.values.toList();
|
return found.values.toList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+1
-1
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.0.0+1
|
version: 1.0.1+2
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.13.4
|
sdk: ^3.13.4
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
HttpOverrides.global = null;
|
||||||
|
|
||||||
|
group('ACK Verification and Timeout Tests', () {
|
||||||
|
test('sendCode returns false when server is unreachable or offline', () async {
|
||||||
|
final remote = ConnectionRemoteDataSource();
|
||||||
|
|
||||||
|
final result = await remote.sendCode(
|
||||||
|
code: '1234567890',
|
||||||
|
suffix: 'enter',
|
||||||
|
pin: '',
|
||||||
|
ip: '127.0.0.1',
|
||||||
|
port: 59999, // Unused port
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result, isFalse);
|
||||||
|
remote.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sendCode returns true only when server responds with success: true', () async {
|
||||||
|
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
server.listen((HttpRequest request) async {
|
||||||
|
await request.drain();
|
||||||
|
if (request.uri.path == '/api/type') {
|
||||||
|
request.response.statusCode = 200;
|
||||||
|
request.response.headers.contentType = ContentType.json;
|
||||||
|
request.response.write(jsonEncode({'status': 'ok', 'success': true}));
|
||||||
|
await request.response.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
final remote = ConnectionRemoteDataSource();
|
||||||
|
final result = await remote.sendCode(
|
||||||
|
code: 'TEST-CODE',
|
||||||
|
suffix: 'enter',
|
||||||
|
pin: '',
|
||||||
|
ip: '127.0.0.1',
|
||||||
|
port: server.port,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result, isTrue);
|
||||||
|
|
||||||
|
await server.close(force: true);
|
||||||
|
remote.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sendCode returns false when server responds with success: false (e.g. paused/error)', () async {
|
||||||
|
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
server.listen((HttpRequest request) async {
|
||||||
|
await request.drain();
|
||||||
|
if (request.uri.path == '/api/type') {
|
||||||
|
request.response.statusCode = 200;
|
||||||
|
request.response.headers.contentType = ContentType.json;
|
||||||
|
request.response.write(jsonEncode({'status': 'paused', 'success': false}));
|
||||||
|
await request.response.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
final remote = ConnectionRemoteDataSource();
|
||||||
|
final result = await remote.sendCode(
|
||||||
|
code: 'TEST-PAUSED',
|
||||||
|
suffix: 'enter',
|
||||||
|
pin: '',
|
||||||
|
ip: '127.0.0.1',
|
||||||
|
port: server.port,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result, isFalse);
|
||||||
|
|
||||||
|
await server.close(force: true);
|
||||||
|
remote.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sendCode returns false when server response times out', () async {
|
||||||
|
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
server.listen((HttpRequest request) async {
|
||||||
|
await request.drain();
|
||||||
|
await Future.delayed(const Duration(milliseconds: 2000));
|
||||||
|
request.response.statusCode = 200;
|
||||||
|
await request.response.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
final remote = ConnectionRemoteDataSource();
|
||||||
|
final stopwatch = Stopwatch()..start();
|
||||||
|
final result = await remote.sendCode(
|
||||||
|
code: 'TEST-TIMEOUT',
|
||||||
|
suffix: 'enter',
|
||||||
|
pin: '',
|
||||||
|
ip: '127.0.0.1',
|
||||||
|
port: server.port,
|
||||||
|
);
|
||||||
|
stopwatch.stop();
|
||||||
|
|
||||||
|
expect(result, isFalse);
|
||||||
|
expect(stopwatch.elapsedMilliseconds, lessThan(3500));
|
||||||
|
|
||||||
|
await server.close(force: true);
|
||||||
|
remote.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
+32
-8
@@ -230,7 +230,7 @@ class BarcodeServerCore:
|
|||||||
|
|
||||||
async def handle_type_post(request: web.Request) -> web.Response:
|
async def handle_type_post(request: web.Request) -> web.Response:
|
||||||
if not self.is_listening:
|
if not self.is_listening:
|
||||||
return web.json_response({"status": "paused", "message": "Server in pausa"}, status=503)
|
return web.json_response({"status": "paused", "message": "Server in pausa", "success": False}, status=503)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = await request.json()
|
data = await request.json()
|
||||||
@@ -240,10 +240,10 @@ class BarcodeServerCore:
|
|||||||
|
|
||||||
required_pin = str(self.config.get("pin", "")).strip()
|
required_pin = str(self.config.get("pin", "")).strip()
|
||||||
if required_pin and pin != required_pin:
|
if required_pin and pin != required_pin:
|
||||||
return web.json_response({"status": "error", "message": "PIN errato"}, status=401)
|
return web.json_response({"status": "error", "message": "PIN errato", "success": False}, status=401)
|
||||||
|
|
||||||
if not code:
|
if not code:
|
||||||
return web.json_response({"status": "error", "message": "Nessun codice fornito"}, status=400)
|
return web.json_response({"status": "error", "message": "Nessun codice fornito", "success": False}, status=400)
|
||||||
|
|
||||||
suffix = data.get("suffix") or self.config.get("suffix", "enter")
|
suffix = data.get("suffix") or self.config.get("suffix", "enter")
|
||||||
success = await self.kb.type_text(code, suffix=suffix)
|
success = await self.kb.type_text(code, suffix=suffix)
|
||||||
@@ -259,7 +259,7 @@ class BarcodeServerCore:
|
|||||||
|
|
||||||
return web.json_response({"status": "ok", "typed": code, "success": success})
|
return web.json_response({"status": "ok", "typed": code, "success": success})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return web.json_response({"status": "error", "message": str(e)}, status=500)
|
return web.json_response({"status": "error", "message": str(e), "success": False}, status=500)
|
||||||
|
|
||||||
async def handle_websocket(request: web.Request) -> web.WebSocketResponse:
|
async def handle_websocket(request: web.Request) -> web.WebSocketResponse:
|
||||||
ws = web.WebSocketResponse(heartbeat=25.0)
|
ws = web.WebSocketResponse(heartbeat=25.0)
|
||||||
@@ -301,12 +301,23 @@ class BarcodeServerCore:
|
|||||||
})
|
})
|
||||||
|
|
||||||
elif msg_type == "scan":
|
elif msg_type == "scan":
|
||||||
|
req_id = payload.get("req_id")
|
||||||
if not authenticated:
|
if not authenticated:
|
||||||
await ws.send_json({"type": "auth_error", "message": "Autenticazione richiesta"})
|
await ws.send_json({
|
||||||
|
"type": "auth_error",
|
||||||
|
"message": "Autenticazione richiesta",
|
||||||
|
"req_id": req_id,
|
||||||
|
})
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if not self.is_listening:
|
if not self.is_listening:
|
||||||
await ws.send_json({"type": "paused", "message": "Server in pausa"})
|
await ws.send_json({
|
||||||
|
"type": "ack",
|
||||||
|
"code": payload.get("code", ""),
|
||||||
|
"success": False,
|
||||||
|
"message": "Server in pausa",
|
||||||
|
"req_id": req_id,
|
||||||
|
})
|
||||||
continue
|
continue
|
||||||
|
|
||||||
code = str(payload.get("code", "")).strip()
|
code = str(payload.get("code", "")).strip()
|
||||||
@@ -323,12 +334,25 @@ class BarcodeServerCore:
|
|||||||
if self.on_scan:
|
if self.on_scan:
|
||||||
self.on_scan(code, client_name, success)
|
self.on_scan(code, client_name, success)
|
||||||
|
|
||||||
await ws.send_json({
|
ack_data = {
|
||||||
"type": "ack",
|
"type": "ack",
|
||||||
"code": code,
|
"code": code,
|
||||||
"success": success,
|
"success": success,
|
||||||
"time": timestamp,
|
"time": timestamp,
|
||||||
})
|
}
|
||||||
|
if req_id is not None:
|
||||||
|
ack_data["req_id"] = req_id
|
||||||
|
await ws.send_json(ack_data)
|
||||||
|
else:
|
||||||
|
ack_data = {
|
||||||
|
"type": "ack",
|
||||||
|
"code": "",
|
||||||
|
"success": False,
|
||||||
|
"message": "Codice vuoto",
|
||||||
|
}
|
||||||
|
if req_id is not None:
|
||||||
|
ack_data["req_id"] = req_id
|
||||||
|
await ws.send_json(ack_data)
|
||||||
|
|
||||||
elif msg_type == "ping":
|
elif msg_type == "ping":
|
||||||
await ws.send_json({"type": "pong"})
|
await ws.send_json({"type": "pong"})
|
||||||
|
|||||||
Reference in new issue
Block a user