discoverBridges static method

Future<List<String>> discoverBridges({
  1. Directory? savedBridgesDir,
  2. bool writeToLocal = true,
})

Searches the network for Philips Hue bridges.

Returns a list of all of their IP addresses.

If saved bridges are not saved to the default folder, provide their location with savedBridgesDir.

Implementation

static Future<List<String>> discoverBridges(
    {Directory? savedBridgesDir, bool writeToLocal = true}) async {
  /// The bridges already saved to this device.
  List<Bridge> savedBridges;

  if (kIsWeb) {
    // cookies instead of local storage (not yet implemented)
    savedBridges = [];
  } else {
    savedBridges = await fetchSavedBridges(savedBridgesDir);
  }

  /// Bridges found using MDNS.
  List<String> bridgesFromMdns;
  if (kIsWeb) {
    // mDNS does not work on web.
    bridgesFromMdns = [];
  } else {
    bridgesFromMdns = await BridgeDiscoveryService.discoverBridgesMdns();
  }

  /// Bridges found using the endpoint method.
  List<String> bridgesFromEndpoint =
      await BridgeDiscoveryService.discoverBridgesEndpoint();

  // Remove duplicates from the two search methods.
  Set<String> uniqueValues = {};
  uniqueValues.addAll(bridgesFromMdns);
  uniqueValues.addAll(bridgesFromEndpoint);

  if (savedBridges.isEmpty) return uniqueValues.toList();

  List<String> ipAddresses = [];

  // Remove the bridges that are already saved to the device from the search
  // results.
  for (String ip in uniqueValues) {
    for (Bridge bridge in savedBridges) {
      if (bridge.ipAddress == null || bridge.ipAddress != ip) {
        ipAddresses.add(ip);
      }
    }
  }

  // Keep locally saved bridges up to date.
  if (writeToLocal) {
    for (String ip in ipAddresses) {
      // This will go through each of the bridges who's IP address have just
      // been collected and tries to connect to them. If there is a successful
      // connection, then this isn't the first time contact has been made with
      // the bridge. In this case, the file will be overridden with the new IP
      // address.
      await firstContact(
        bridgeIpAddr: ip,
        savedBridgesDir: savedBridgesDir,
        writeToLocal: writeToLocal,
        controller: DiscoveryTimeoutController(timeoutSeconds: 1),
      );
    }
  }

  return ipAddresses;
}