findZipDevicesFromLocal function
Implementation
Future<List<ZipLocalDevice>> findZipDevicesFromLocal(int timeOut) async {
var DESTINATION_ADDRESS = InternetAddress("255.255.255.255");
List<ZipLocalDevice> zipLocalDeviceList = [];
await RawDatagramSocket.bind(InternetAddress.anyIPv4, 10181)
.then((RawDatagramSocket socket) async {
print('Datagram socket ready to receive');
print('${socket.address.address}:${socket.port}');
socket.broadcastEnabled = true;
socket.send(
'{"cmd":"device report"}'.codeUnits, DESTINATION_ADDRESS, 10182);
socket.listen((RawSocketEvent e) {
Datagram? d = socket.receive();
if (d == null) {
return;
}
String message = new String.fromCharCodes(d.data).trim();
print('Datagram from ${d.address.address}:${d.port}: ${message}');
Map<String, dynamic> device = jsonDecode(message);
print(device);
//去掉非本格式数据
if (!device.containsKey("name") ||
!device.containsKey("ip") ||
!device.containsKey("mac") ||
!device.containsKey("type") ||
!device.containsKey("type_name")) {
return;
}
ZipLocalDevice zipLocalDevice = ZipLocalDevice.fromMap(device);
//去重
for (int i = 0; i < zipLocalDeviceList.length; i++) {
if (zipLocalDeviceList[i].mac == zipLocalDevice.mac) {
return;
}
}
zipLocalDeviceList.add(zipLocalDevice);
});
socket.send(
'{"cmd":"device report"}'.codeUnits, DESTINATION_ADDRESS, 10182);
await Future.delayed(Duration(seconds: timeOut))
.then((value) => socket.close());
print("findZipDevicesFromLocal:${zipLocalDeviceList.length}");
});
return zipLocalDeviceList;
}