81 lines
2.2 KiB
Dart
81 lines
2.2 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
class DiscoveredServer {
|
|
final String ip;
|
|
final int port;
|
|
final String serverName;
|
|
final String wsUrl;
|
|
final String httpUrl;
|
|
final bool pinRequired;
|
|
|
|
DiscoveredServer({
|
|
required this.ip,
|
|
required this.port,
|
|
required this.serverName,
|
|
required this.wsUrl,
|
|
required this.httpUrl,
|
|
required this.pinRequired,
|
|
});
|
|
|
|
factory DiscoveredServer.fromJson(Map<String, dynamic> json) => DiscoveredServer(
|
|
ip: json['ip'] as String? ?? '',
|
|
port: json['port'] as int? ?? 8765,
|
|
serverName: json['server_name'] as String? ?? 'PC Server',
|
|
wsUrl: json['ws_url'] as String? ?? '',
|
|
httpUrl: json['http_url'] as String? ?? '',
|
|
pinRequired: json['pin_required'] as bool? ?? false,
|
|
);
|
|
}
|
|
|
|
class DiscoveryService {
|
|
static const int udpPort = 8766;
|
|
|
|
static Future<List<DiscoveredServer>> discover({Duration timeout = const Duration(seconds: 3)}) async {
|
|
final Map<String, DiscoveredServer> found = {};
|
|
RawDatagramSocket? socket;
|
|
|
|
try {
|
|
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
|
|
socket.broadcastEnabled = true;
|
|
|
|
// Broadcast message to local network
|
|
final data = utf8.encode('DISCOVER_BARCODE_SERVER');
|
|
socket.send(data, InternetAddress('255.255.255.255'), udpPort);
|
|
|
|
final completer = Completer<List<DiscoveredServer>>();
|
|
|
|
final sub = socket.listen((event) {
|
|
if (event == RawSocketEvent.read) {
|
|
final dg = socket?.receive();
|
|
if (dg != null) {
|
|
try {
|
|
final raw = utf8.decode(dg.data).trim();
|
|
final json = jsonDecode(raw) as Map<String, dynamic>;
|
|
if (json['type'] == 'discover_response') {
|
|
final server = DiscoveredServer.fromJson(json);
|
|
final key = '${server.ip}:${server.port}';
|
|
found[key] = server;
|
|
}
|
|
} catch (_) {}
|
|
}
|
|
}
|
|
});
|
|
|
|
Timer(timeout, () {
|
|
sub.cancel();
|
|
socket?.close();
|
|
if (!completer.isCompleted) {
|
|
completer.complete(found.values.toList());
|
|
}
|
|
});
|
|
|
|
return await completer.future;
|
|
} catch (e) {
|
|
socket?.close();
|
|
return [];
|
|
}
|
|
}
|
|
}
|