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 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> discover({Duration timeout = const Duration(seconds: 3)}) async { final Map 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>(); 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; 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 []; } } }