discover static method

Future<List<LinuxCastDevice>> discover({
  1. Duration timeout = const Duration(seconds: 5),
})

Discovers IPv4 Cast endpoints through mDNS. Timeout applies per query.

Implementation

static Future<List<LinuxCastDevice>> discover({
  Duration timeout = const Duration(seconds: 5),
}) async {
  final client = MDnsClient();
  final devices = <String, LinuxCastDevice>{};
  try {
    await client.start();
    final services = await client
        .lookup<PtrResourceRecord>(
          ResourceRecordQuery.serverPointer('_googlecast._tcp.local'),
          timeout: timeout,
        )
        .toList();
    await Future.wait(
      services.map((ptr) async {
        final records = await client
            .lookup<SrvResourceRecord>(
              ResourceRecordQuery.service(ptr.domainName),
              timeout: timeout,
            )
            .toList();
        final texts = await client
            .lookup<TxtResourceRecord>(
              ResourceRecordQuery.text(ptr.domainName),
              timeout: timeout,
            )
            .toList();
        final properties = <String, String>{};
        for (final text in texts) {
          for (final entry in text.text.split('\n')) {
            final separator = entry.indexOf('=');
            if (separator > 0) {
              properties[entry.substring(0, separator)] = entry.substring(
                separator + 1,
              );
            }
          }
        }
        for (final record in records) {
          final addresses = await client
              .lookup<IPAddressResourceRecord>(
                ResourceRecordQuery.addressIPv4(record.target),
                timeout: timeout,
              )
              .toList();
          for (final address in addresses) {
            final id = properties['id'] ?? ptr.domainName;
            devices[id] = LinuxCastDevice(
              id: id,
              name: properties['fn'] ?? ptr.domainName,
              host: address.address.address,
              port: record.port,
            );
          }
        }
      }),
    );
    return devices.values.toList();
  } finally {
    client.stop();
  }
}