start method
Implementation
Future 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();
void Function(InternetAddress, [NetworkInterface]) joinMulticastFunction = _socket!.joinMulticast;
for (var interface in _interfaces) {
withAddress(InternetAddress address) {
try {
Function.apply(joinMulticastFunction, [
address
], {
#interface: interface
});
} on NoSuchMethodError {
Function.apply(joinMulticastFunction, [
address,
interface
]);
}
}
try {
withAddress(_v4_Multicast);
} on SocketException {
try {
withAddress(_v6_Multicast);
} on OSError {
}
}
}
_socket!.broadcastEnabled = true;
_socket!.multicastHops = 100;
_socket!.listen((RawSocketEvent e) async {
if (e == RawSocketEvent.read) {
var packet = _socket!.receive()!;
_socket!.writeEventsEnabled = true;
try {
var string = utf8.decode(packet.data);
var lines = string.split("\r\n");
var firstLine = lines.first;
if (firstLine.trim() == "M-SEARCH * HTTP/1.1") {
var map = {};
for (String line in lines.skip(1)) {
if (line.trim().isEmpty) continue;
if (!line.contains(":")) continue;
var parts = line.split(":");
var key = parts.first;
var value = parts.skip(1).join(":");
map[key.toUpperCase()] = value;
}
if (map["ST"] is String) {
var search = map["ST"];
var devices = await respondToSearch(search, packet, map as Map<String, String>);
for (var dev in devices) {
_socket!.send(utf8.encode(dev), packet.address, packet.port);
}
}
}
} catch (e) {
}
}
});
await notify();
}