discoverDevices method

Future<List<DiscoveredDevice>> discoverDevices({
  1. String? type,
  2. Duration timeout = const Duration(seconds: 5),
})

Implementation

Future<List<DiscoveredDevice>> discoverDevices(
    {String? type, Duration timeout = const Duration(seconds: 5)}) {
  return discoverClients(timeout: timeout).then((clients) {
    if (clients.isEmpty) {
      return [];
    }

    final uuids = clients
        .where((client) => client.usn != null)
        .map((client) => client.usn!.split('::').first)
        .toSet();
    final devices = <DiscoveredDevice>[];

    for (var uuid in uuids) {
      final deviceClients = clients.where((client) {
        return client.usn != null && client.usn!.split('::').first == uuid;
      }).toList();
      final location = deviceClients.first.location;
      final serviceTypes = deviceClients.map((it) => it.st).toSet().toList();
      final device = DiscoveredDevice();
      device.serviceTypes = serviceTypes;
      device.uuid = uuid;
      device.location = location;
      if (type == null || serviceTypes.contains(type)) {
        devices.add(device);
      }
    }

    for (var client in clients.where((it) => it.usn == null)) {
      final device = DiscoveredDevice();
      device.serviceTypes = [client.st];
      device.uuid = null;
      device.location = client.location;
      if (type == null || device.serviceTypes.contains(type)) {
        devices.add(device);
      }
    }

    return devices;
  });
}