react-native-wifi-reborn icon indicating copy to clipboard operation
react-native-wifi-reborn copied to clipboard

Wifi connection to a network without internet access

Open esleybonomo opened this issue 8 months ago • 2 comments

I have a project that connects WiFi to an IoT device, generating the APK in --dev-client mode, everything works perfectly, however when I generate the APK for testing in QA, it doesn't work, it seems to create a second network and it doesn't connect to the available.

image

useEffect(() => {
    (async () => {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'A permissão de localização é necessária para conexões WiFi',
          message:
            'Este aplicativo precisa de permissão de localização, ' + 
            'pois isso é necessário para digitalizar redes Wi-Fi.',
          buttonNegative: 'DENY',
          buttonPositive: 'ALLOW',
        },
      );
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        return;
      }
      const location = await Location.getCurrentPositionAsync({});
      
      enableWifiUsage().then(() => {
        console.debug("WiFi local ativado. Conectando...");
        connectToWifi(macAddress, setIsLoading, wifiGatewayPassword, setNewMacAddress).then(() => {
          console.debug("Conectado!");
          getDeviceConfiguration().then(() => {
            console.debug("Carregou os dados de rede do equipamento.");
          },
          (e) => {
            let msgError = "Erro ao carregar dados de rede do equipamento. " + e.error;
            Toast.show({
              type: 'error',
              text1: msgError
            });
            throw new Error(msgError);
          });
        });
      });
    })();
  }, []);

  const wifiGatewayPassword = async () => {
    const response = await services.gatewayWifiPassword(macAddress);
    const wifiPassword = response.data;
    setGatewayPassword(wifiPassword);
    return Promise.resolve(wifiPassword)
  };

  const getDeviceConfiguration = ( async () => {
    const responseData = await services.GetDeviceConfiguration();
    const response = responseData.data
    setSsid(response.net_ssid);
    setPassword(response.net_pass);
  });

I created WIfiManager.js

import WifiManager from 'react-native-wifi-reborn';
import Toast from 'react-native-toast-message';

export const enableWifiUsage = async () => {
  try {
    await WifiManager.forceWifiUsageWithOptions(true, { noInternet: true }).then(() => {
      console.debug("Todas as solicitações de rede serão roteadas para a rede WiFi sem Internet.");
    });
  } catch (error) {
    console.error("Falhou em permitir o uso de Wi-Fi sem internet: " + error.message);
  }
};

export const disableWifiUsage = async () => {
  try {
    await WifiManager.forceWifiUsageWithOptions(false, { noInternet: true }).then(() => {
      console.debug("As solicitações de rede serão roteadas para a rede padrão.");
    });
  } catch (error) {
    console.error("Falha ao desativar o uso de WiFi: " + error.message);
  }
};

export const connectToWifi = async (macAddress, setIsLoading, wifiGatewayPassword, setNewMacAddress) => {
  const newMacAddress = macAddress.replace(/:/g, '-');
  setNewMacAddress(newMacAddress);
  const ssid = 'Connect Lite ' + newMacAddress;
  setIsLoading(true);
  
  const password = await wifiGatewayPassword();
  try {
    WifiManager.isEnabled().then((enabled) => {
      if (!enabled) {
        WifiManager.setEnabled(true);
        console.debug("Wifi Enabled");
      }
    })

    await WifiManager.connectToProtectedSSID(ssid, password, false, false).then(() => {
      Toast.show({
        type: 'success',
        text1: 'Conectado à rede Wi-Fi',
        text2: ssid
      });
    });
  } catch (error) {
    Toast.show({
      type: 'error',
      text1: 'Erro ao conectar à rede Wi-Fi do gateway',
      text2: error.message
    });
  } finally {
    setIsLoading(false);
  }
};

Can anyone help me identify where my error is?

esleybonomo avatar Jun 20 '24 21:06 esleybonomo