discoverBridgesMdns static method

Future<List<DiscoveredBridge>> discoverBridgesMdns()

Searches the network for bridges using mDNS.

Implementation

static Future<List<DiscoveredBridge>> discoverBridgesMdns() async {
  final List<DiscoveredBridge> bridges = [];

  final Set<String> discoveredPtr = {};
  final Set<SrvResourceRecord> discoveredSvr = {};
  final Set<IPAddressResourceRecord> discoveredIp = {};

  final MDnsClient client = MDnsClient();

  await client.start();

  await for (final PtrResourceRecord ptr in client.lookup<PtrResourceRecord>(
      ResourceRecordQuery.serverPointer("_hue._tcp.local"))) {
    if (!discoveredPtr.add(ptr.domainName)) continue;

    await for (final SrvResourceRecord srv
        in client.lookup<SrvResourceRecord>(
            ResourceRecordQuery.service(ptr.domainName))) {
      if (!discoveredSvr.add(srv)) continue;

      await for (final IPAddressResourceRecord ip
          in client.lookup<IPAddressResourceRecord>(
              ResourceRecordQuery.addressIPv4(srv.target))) {
        if (!discoveredIp.add(ip)) continue;

        final String target = srv.target;

        final String rawIdFromMdns;
        if (target.contains('.')) {
          rawIdFromMdns = target.substring(0, target.indexOf('.'));
        } else {
          rawIdFromMdns = target;
        }

        bridges.add(
          DiscoveredBridge.fromMdns(
            rawIdFromMdns: rawIdFromMdns,
            ipAddress: ip.address.address,
          ),
        );
      }
    }
  }

  client.stop();

  return bridges;
}