kirillzyusko / react-native-wifi-p2p

Library that provide access for working with wi-fi direct (p2p) module in android.
164 stars 32 forks source link

Help required #100

Open anuragkaushik10 opened 5 days ago

anuragkaushik10 commented 5 days ago

Hey @kirillzyusko and team,

I am building an application where one user is the receiver and the other is the sender, even when there is no internet connection.

I have achieved this feature using react-native-tcp, but it requires too much manual intervention. To make it more automatic, I discovered this library.

However, I am now unsure if this library supports large base64 strings.

Currently, I can call the connect() function successfully, as it doesn't throw an error, indicating the devices are connected.

My next step is to send the actual base64 string to the receiver.

Here is my actual code:

import React, { useEffect, useState } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Button,
  PermissionsAndroid,
  TouchableOpacity,
  Alert,
} from 'react-native';
import WifiP2P, {
  connect,
  initialize,
  receiveMessage,
  sendMessage,
  startDiscoveringPeers,
  stopDiscoveringPeers,
  subscribeOnPeersUpdates,
} from 'react-native-wifi-p2p';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';

const P2P = () => {
  const [peers, setPeers] = useState(null);
  const [data, setData] = useState('');
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    checkPermission();
  }, []);

  const checkPermission = async () => {
    try {
      const locationPermission = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
      if (locationPermission === RESULTS.GRANTED) {
        initializeWiFiDirect();
      } else {
        requestPermission();
      }
    } catch (error) {
      console.error('Error checking permission:', error);
    }
  };

  const requestPermission = async () => {
    try {
      const result = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
      if (result === RESULTS.GRANTED) {
        initializeWiFiDirect();
      } else {
        console.log('Location permission denied');
      }
    } catch (error) {
      console.error('Error requesting permission:', error);
    }
  };

  const initializeWiFiDirect = async () => {
    try {
      console.log('WiFi Direct initialized');
      subscribeToPeersChanges();
    } catch (error) {
      console.error('Failed to initialize WiFi Direct:', error);
    }
  };

  const subscribeToPeersChanges = () => {
    const discoverPeersSubscription = subscribeOnPeersUpdates((deviceList) => {
      setPeers(deviceList);
    });
    return () => {
      discoverPeersSubscription.remove();
    };
  };

  const discoverPeers = async () => {
    try {
      setPeers(null);
      await startDiscoveringPeers();
    } catch (error) {
      console.error('Error discovering peers:', error);
    }
  };

  const connectToPeer = async (deviceAddress) => {
    try {
      console.log(deviceAddress);
      await connect(deviceAddress);
      Alert.alert('Connected');
      setConnected(true);
      sendData(deviceAddress);
      await stopDiscoveringPeers();
    } catch (err) {
      console.log(err);
    }
  };

  const sendData = async (deviceAddress) => {
    try {
      await sendMessage(deviceAddress, 'anurag');
      Alert.alert('Data Sent');
    } catch (e) {
      console.log(e);
    }
  };

  const receiveData = async () => {
    try {
      console.log('receiveData');
      receiveMessage()
        .then((msg) => console.log('Message received successfully', msg))
        .catch((err) => console.log('Error while receiving message', err));

      Alert.alert('Data Received');
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>WiFi Direct Example</Text>
      <Button title="Discover Peers" onPress={discoverPeers} />
      <Text style={styles.subtitle}>Available Peers:</Text>
      {peers?.devices.length > 0 &&
        peers?.devices.map((peer) => (
          <TouchableOpacity
            style={{ backgroundColor: 'red', padding: 20 }}
            key={peer.deviceAddress}
            onPress={() => connectToPeer(peer.deviceAddress)}>
            <Text style={{ color: 'white' }}>{peer.deviceName}</Text>
          </TouchableOpacity>
        ))}
      <Button title="Receive Data" onPress={receiveData} />
      {data && <Text>{data}</Text>}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
 }
})

Please take a look and let me know if any further adjustments are required.

kirillzyusko commented 4 days ago

What is the size of the string? Does it exceed 16Mb?

anuragkaushik10 commented 4 days ago

Thankyou for your prompt response.

String size will not exceed 16mb

kirillzyusko commented 4 days ago

Okay, why can't you use sendFile? I guess it's more suitable?

But overall sending base64 also should work - does it throw any particular error?

anuragkaushik10 commented 4 days ago

Here you go getting same error when using sendFile() and sendMessage()

image

kirillzyusko commented 4 days ago

@anuragkaushik10 do you call getConnectionInfo? https://github.com/kirillzyusko/react-native-wifi-p2p?tab=readme-ov-file#sendmessagemessage

anuragkaushik10 commented 4 days ago

Okay I will do but before that.

The steps ->

  1. Search for devices using startDiscoveringPeers();
  2. After this by passing the device address I will connect the device using connect(deviceAddress)
  3. Start to using sendMessage or sendFile functions on sender side and simultaneously call receiveMessage and receiveFile functions on receiver side.
anuragkaushik10 commented 4 days ago

Hey when following the steps mentioned in README for sending message.

Calling createGroup() gives the following error

image

++++

Also calling getConnectionInfo() after calling createGroup() gives the following message

{"groupFormed": true, "groupOwnerAddress": {"hostAddress": "host:name", "isLoopbackAddress": false}, "isGroupOwner": false}

kirillzyusko commented 3 days ago

Calling createGroup() gives the following error

@anuragkaushik10 Can you share adb logs?