connect method

Future<void> connect(
  1. WifiScan network, [
  2. String? password
])

Implementation

Future<void> connect(WifiScan network, [String? password]) async {
  LogbotLogger().debug("connect()", network.id.toString());
  setState(() {
    isLoading = true;
  });
  try {
    await LogbotSetupApiManager.network.connectWifi(
      network.id!,
      SecurityWifi(
        password: password,
      ),
    );

    /// Should retry a few times before throwing an error
    int attempt = 1;
    int maxAttempts = 10;
    int delay = 1;
    WifiStatus? status;
    while (attempt <= maxAttempts) {
      status = await LogbotSetupApiManager.network.getWifiStatus();
      if (status!.connection!.state == ConnectionStatusState.ACTIVATED &&
          status.connection!.flags.contains(ConnectionStatusFlags.iP4READY)) {
        setState(() {
          isConnected = true;
          formData = {
            "connection": {
              "id": network.connection?.id ?? "",
              "band": network.connection?.band ?? "",
            },
            "ipv4": {
              "address": status?.ipv4?.address ?? "",
              "prefix": status?.ipv4?.prefix ?? 24,
              "gateway": status?.ipv4?.gateway ?? "",
              "dns": {
                "primary": status?.ipv4?.dns?.primary ?? "",
                "secondary": status?.ipv4?.dns?.secondary ?? "",
              }
            }
          };
        });
        break;
      }
      await Future.delayed(Duration(seconds: delay));
      attempt++;
    }

    /// If I reached max attempts, throws error
    if (attempt == maxAttempts) {
      throw Error(
          message: "WiFi not connected",
          details: status?.connection!.flags.toString());
    }

    /// If has connected, download the current network config
    await initApiCall();
    setState(() {});
  } catch (e) {
    LogbotLogger().error("connect()", e.toString());
  } finally {
    setState(() {
      isLoading = false;
    });
  }
}