start method
Implementation
Future<void> start() async {
await stop();
_timer = Timer.periodic(const Duration(seconds: 5), (_) {
if (_socket != null) {
notify();
}
});
_socket = await RawDatagramSocket.bind('0.0.0.0', 1900);
_interfaces = await NetworkInterface.list();
final void Function(InternetAddress, [NetworkInterface])
joinMulticastFunction = _socket!.joinMulticast;
for (var interface in _interfaces) {
void withAddress(InternetAddress address) {
try {
Function.apply(
joinMulticastFunction, [address], {#interface: interface});
} on NoSuchMethodError {
Function.apply(joinMulticastFunction, [address, interface]);
}
}
try {
withAddress(_v4Multicast);
} on SocketException {
try {
withAddress(_v6Multicast);
} catch (_) {}
}
}
_socket!.broadcastEnabled = true;
_socket!.multicastHops = 100;
_socket!.listen((RawSocketEvent e) async {
if (e == RawSocketEvent.read) {
final packet = _socket!.receive()!;
_socket!.writeEventsEnabled = true;
try {
final string = utf8.decode(packet.data);
final lines = string.split('\r\n');
final firstLine = lines.first;
if (firstLine.trim() == 'M-SEARCH * HTTP/1.1') {
final map = <String, String>{};
for (String line in lines.skip(1)) {
if (line.trim().isEmpty) continue;
if (!line.contains(':')) continue;
final parts = line.split(':');
final key = parts.first;
final value = parts.skip(1).join(':');
map[key.toUpperCase()] = value;
}
if (map['ST'] is String) {
final search = map['ST'];
final devices = await respondToSearch(search, packet, map);
for (var dev in devices) {
_socket!.send(utf8.encode(dev), packet.address, packet.port);
}
}
}
} catch (_) {}
}
});
await notify();
}