firstContact static method

Future<Bridge?> firstContact({
  1. required String bridgeIpAddr,
  2. Directory? savedBridgesDir,
  3. bool writeToLocal = true,
  4. DiscoveryTimeoutController? controller,
})

Initiates the first contact between this device and the given bridge.

Once this method has been called, the user will have 10 seconds by default, or how ever many have been set in controller, to press the button on their bridge to confirm they have physical access to it.

In the event of a successful pairing, this method returns a bridge object that represents the bridge it just connected to. Before it returns the bridge, if writeToLocal is true, it will write it to local storage to be saved for later.

If writing saved bridges to a non-default location, provide that location with savedBridgesDir.

controller gives more control over this process. It lets you decide how many seconds the user has to press the button on their bridge. It also gives the ability to cancel the discovery process at any time.

If the pairing fails, this method returns null.

Implementation

static Future<Bridge?> firstContact({
  required String bridgeIpAddr,
  Directory? savedBridgesDir,
  bool writeToLocal = true,
  DiscoveryTimeoutController? controller,
}) async {
  final DiscoveryTimeoutController timeoutController =
      controller ?? DiscoveryTimeoutController();

  Map<String, dynamic>? response;

  /// Used as the suffix of this device's name in the bridge whitelist.
  String device;
  if (kIsWeb) {
    device = "web";
  } else {
    switch (Platform.operatingSystem) {
      case "android":
      case "fuchsia":
      case "linux":
        device = Platform.operatingSystem;
        break;
      case "ios":
        device = "iPhone";
        break;
      case "macos":
        device = "mac";
        break;
      case "windows":
        device = "pc";
        break;
      default:
        device = "device";
    }
  }

  String? appKey;

  String body =
      JsonTool.writeJson({ApiFields.deviceType: "FlutterHue#$device"});

  // Try for [timeoutSeconds] to connect with the bridge.
  int counter = 0;
  await Future.doWhile(
    () => Future.delayed(const Duration(seconds: 1)).then(
      (value) async {
        counter++;

        // Timeout after [timeoutSeconds].
        if (counter >= timeoutController.timeoutSeconds) return false;

        // Cancel if called to do so, early.
        if (timeoutController.cancelDiscovery) {
          timeoutController.cancelDiscovery = false;
          return false;
        }

        response = await HueHttpClient.post(
          url: "https://$bridgeIpAddr/api",
          applicationKey: null,
          body: body,
        );

        if (response == null || response!.isEmpty) return true;

        try {
          if (response!.containsKey(ApiFields.error)) {
            return response![ApiFields.error][ApiFields.description] ==
                "link button not pressed";
          } else {
            appKey = response![ApiFields.success]["username"];
            return appKey!.isEmpty;
          }
        } catch (_) {
          return true;
        }
      },
    ),
  );

  if (appKey == null) return null;

  // Upon successful connection, get the bridge details.
  Map<String, dynamic>? bridgeJson = await HueHttpRepo.get(
    bridgeIpAddr: bridgeIpAddr,
    applicationKey: appKey!,
    resourceType: ResourceType.bridge,
  );

  if (bridgeJson == null) return null;

  Bridge bridge = Bridge.fromJson(bridgeJson);
  bridge = bridge.copyWith(ipAddress: bridgeIpAddr, applicationKey: appKey);

  if (bridge.id.isEmpty) return null;

  // Save the bridge locally.
  if (writeToLocal) {
    _writeLocalBridge(bridge, savedBridgesDir);
  }

  return bridge;
}